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 (11)

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
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

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.

Collapse
 
intermundos profile image
intermundos

Deep clone can be done using structuredClone

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

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

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

Thank you.

Collapse
 
lavinia_viana_2305 profile image
lavinia viana

muito obg, isso pode ser muito útil na hora de codar.

Collapse
 
hbthepencil profile image
HB_the_Pencil

This is great! Currying a function looks really cool!

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

Thank you.

Collapse
 
daniel_ma_4ea0d9971ef2dcf profile image
Daniel Ma

EchoAPI has truly elevated my JavaScript development experience, offering powerful tools for efficient API management.

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

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!