DEV Community

Nozibul Islam
Nozibul Islam

Posted on

Master 6 Powerful JavaScript Functions! 💻

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));

Enter fullscreen mode Exit fullscreen mode

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));

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Incorporating these techniques can greatly improve your JavaScript code's performance and readability. Let’s make coding faster, cleaner, and more efficient!

Top comments (5)

Collapse
 
ayasa_siddika_99689bebcf0 profile image
Ayasa Siddika

Your post is amazing! The explanation of each function is clear and straightforward. This kind of content is very helpful for new developers. Thanks for sharing!

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

Thank you.

Collapse
 
oculus42 profile image
Samuel Rouse

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 and throttle 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.

Collapse
 
intermundos profile image
intermundos

Deep clone can be done using structuredClone

Collapse
 
hbthepencil profile image
HB_the_Pencil

This is great! Currying a function looks really cool!