DEV Community

Cover image for 6 Essential JavaScript Functions Every Developer Should Know
Vishal Yadav
Vishal Yadav

Posted on

6 Essential JavaScript Functions Every Developer Should Know

JavaScript is a versatile language that powers much of the web today. Among its many features, certain functions stand out for their utility and performance optimization. In this blog, we will explore six essential JavaScript functions that can enhance your coding toolkit: Debounce, Throttle, Currying, Memoization, Deep Clone, and a bonus function for good measure.

1. Debounce Function

The debounce function is a powerful tool for limiting the rate at which a function can fire. This is particularly useful for optimizing performance in scenarios like window resizing, scrolling, or keystroke events. By ensuring that a function only executes after a specified delay since the last invocation, it helps prevent performance bottlenecks.

function debounce(fn, delay) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn.apply(this, args), delay);
    };
}

// Usage
const logResize = debounce(() => console.log('Resized!'), 2000);
window.addEventListener('resize', logResize);
Enter fullscreen mode Exit fullscreen mode

2. Throttle Function

The throttle function ensures that a function is executed at most once in a specified timeframe. This is especially beneficial for events that can trigger rapidly, such as scrolling or resizing.

function throttle(fn, limit) {
    let lastFunc;
    let lastRan;
    return function(...args) {
        if (!lastRan) {
            fn.apply(this, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(() => {
                if ((Date.now() - lastRan) >= limit) {
                    fn.apply(this, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}

// Usage
const logScroll = throttle(() => console.log('Scrolled!'), 2000);
window.addEventListener('scroll', logScroll);
Enter fullscreen mode Exit fullscreen mode

3. Currying Function

Currying is a functional programming technique that transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This allows for greater flexibility and reusability of functions.

function curry(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        }
        return function(...args2) {
            return curried.apply(this, [...args, ...args2]);
        };
    };
}

// Usage
function add(a, b, c) {
    return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // Output: 6
Enter fullscreen mode Exit fullscreen mode

4. Memoization Function

Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. This can significantly improve performance for functions with expensive computations.

function memoize(fn) {
    const cache = {};
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache[key]) {
            return cache[key];
        }
        const result = fn.apply(this, args);
        cache[key] = result;
        return result;
    };
}

// Usage
const fibonacci = memoize(n => (n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2)));
console.log(fibonacci(40)); // Output: 102334155
Enter fullscreen mode Exit fullscreen mode

5. Deep Clone Function

A deep clone function creates a new object that is a deep copy of the original object. This ensures that nested objects are also copied rather than referenced.

function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

// Usage
const originalObject = { x: 1, y: { z: 2 } };
const clonedObject = deepClone(originalObject);
clonedObject.y.z = 3;
console.log(originalObject.y.z); // Output: 2
Enter fullscreen mode Exit fullscreen mode

6. Flatten Array Function

As a bonus, we introduce the flatten array function, which transforms a nested array into a single-dimensional array. This is useful for simplifying data structures.

function flattenArray(arr) {
    return arr.reduce((accumulator, currentValue) => 
        accumulator.concat(Array.isArray(currentValue) ? flattenArray(currentValue) : currentValue), []);
}

// Usage
const nestedArray = [1, [2, [3, 4], 5], 6];
const flatArray = flattenArray(nestedArray);
console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Conclusion

These six JavaScript functions—Debounce, Throttle, Currying, Memoization, Deep Clone, and Flatten Array—are essential tools in any developer's toolkit. They not only enhance performance but also promote cleaner and more maintainable code. By incorporating these functions into your projects, you can optimize your applications and improve user experience significantly. Happy coding!

Top comments (2)

Collapse
 
santinell profile image
Pavel Evdokimov

I would suggest to use built-in function for deep clone called structuredClone
developer.mozilla.org/en-US/docs/W...

Collapse
 
vyan profile image
Vishal Yadav

Yes 👍