How JavaScript’s Once() Function Works

Posted by

The once function is a higher-order function that returns a new function that can only be called once. After the first call, the returned function will always return the same value without actually calling the original function again.

Here’s a detailed guide on how to use the once function in JavaScript:

  1. First, let’s define the once function. This function takes a function (which we will call “fn”) as an argument and returns a new function that can only be called once.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

function once(fn) {
  let called = false;
  let result;

  return function(...args) {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  }
}

[/dm_code_snippet]

  1. Now let’s use the once function to create a new function that can only be called once.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

function greet(name) {
  console.log(`Hello, ${name}!`);
}

const greetOnce = once(greet);

[/dm_code_snippet]

  1. Now we can call the greetOnce function just like we would call the original greet function, but it will only be called once.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

greetOnce('Alice');
greetOnce('Bob');

// Output:
// Hello, Alice!

[/dm_code_snippet]

  1. In this example, the greetOnce function is called twice, but the greet function is only called once. After the first call, the greetOnce function will always return the same value without actually calling the greet function again.
  2. The once function can be useful for ensuring that a function is only called once, for example to initialize a resource that should only be initialized once.

I hope this helps! Let me know if you have any questions.