Master 6 Powerful JavaScript Functions!
Check out these essential functions every web developer should know to make your code cleaner and more efficient:
1️⃣ Debounce:
Optimize performance by limiting function executions. Ideal for handling events like resizing or typing.
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Example usage:
window.addEventListener('resize', debounce(() => {
console.log('Window resized');
}, 500));
2️⃣ Throttle:
Control execution rates to avoid overwhelming frequent events like scrolling or window resizing.
function throttle(func, delay) {
let lastTime = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}
};
}
// Example usage:
window.addEventListener('scroll', throttle(() => {
console.log('Scroll event triggered');
}, 500));
3️⃣ Currying:
Transform functions into sequences, processing one argument at a time for more modular and flexible code.
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function (...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
}
};
}
// Example usage:
function sum(a, b, c) {
return a + b + c;
}
const curriedSum = curry(sum);
console.log(curriedSum(1)(2)(3)); // Output: 6
4️⃣ Memoization:
Speed up your code by caching function results, avoiding unnecessary re-computations.
function memoize(func) {
const cache = {};
return function (...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
} else {
const result = func.apply(this, args);
cache[key] = result;
return result;
}
};
}
// Example usage:
const factorial = memoize(function (n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
});
console.log(factorial(5)); // Output: 120
console.log(factorial(5)); // Output: 120 (from cache)
5️⃣ Deep Clone:
Make precise copies of complex objects without any reference issues.
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(deepClone);
}
const clonedObj = {};
for (const key in obj) {
clonedObj[key] = deepClone(obj[key]);
}
return clonedObj;
}
// Example usage:
const original = { a: 1, b: { c: 2 } };
const copy = deepClone(original);
console.log(copy); // Output: { a: 1, b: { c: 2 } }
console.log(copy.b === original.b); // Output: false
Incorporating these techniques can greatly improve your JavaScript code's performance and readability. Let’s make coding faster, cleaner, and more efficient!
Top comments (11)
Thanks for publishing this list. I am a big fan of higher order functions, and these can be really helpful functions.
I do think that more explanation of
debounce
andthrottle
would be helpful.Debounce can be called many times but will not run until they delay elapses after the most recent call. If you have a debounce delay of 150 milliseconds and call it every 100 milliseconds, it will not run until you stop calling it, and will run with the last values it was passed.
Throttle can be called many times but will not run until the delay elapses after the most recent run. If you have a throttle delay of 150 milliseconds and call it every 100 milliseconds, it will run every 150 milliseconds with the most recent values it was passed.
For both functions, information may be discarded if multiple calls occur during the delay.
Thank you so much for the thoughtful feedback! 😊 I’m glad to hear you’re a fan of higher-order functions—they’re truly powerful in JavaScript.
Deep clone can be done using structuredClone
Yes, that's correct! The structuredClone method is a built-in way in JavaScript to create a deep clone of objects, including those with nested structures
Thank you.
muito obg, isso pode ser muito útil na hora de codar.
This is great! Currying a function looks really cool!
Thank you.
EchoAPI has truly elevated my JavaScript development experience, offering powerful tools for efficient API management.
Thank you for sharing your thoughts! I'm glad to hear that EchoAPI has had such a positive impact on your JavaScript development workflow. It truly makes managing APIs more seamless and efficient!