12. Advanced JavaScript Utilities
These advanced techniques and utilities help you write faster, more efficient, and more maintainable JavaScript.
12.1 Performance
Throttling
Limits how often a function runs. Useful for scroll/resize events.
function throttle(fn, delay) {
let last = 0;
return function(...args) {
let now = Date.now();
if (now - last > delay) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener('resize', throttle(() => {
console.log('Resized!');
}, 500));
Debouncing
Delays a function until after a pause. Great for search boxes.
function debounce(fn, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
document.getElementById('search').addEventListener('input', debounce(e => {
console.log('Searching:', e.target.value);
}, 300));
12.2 JSON Handling
JSON.parse() & JSON.stringify()
Convert between objects and JSON strings.
let obj = {a:1};
let str = JSON.stringify(obj); // '{"a":1}'
let parsed = JSON.parse(str); // {a:1}
Tip: Always validate JSON before parsing from untrusted sources.
Congratulations! You’ve reached the end of JavaScript Mastery. Keep practicing and building real projects to solidify your knowledge.