What is Function Closure in JavaScript?

By Hemanta Sundaray on 2022-12-05

Function closure in JavaScript refers to the ability of a function to remember and access its lexical scope even when the function is executed outside of its lexical scope.

When a function is executed outside of its lexical scope, it means that the function is being called from a different context than the one in which it was defined.

Note: In JavaScript, a function's lexical scope is the context in which it was defined. This includes any variables that are defined in the outer scopes of the function.

Here is a simple example to illustrate function closure in JavaScript:

function outer() {
  let x = 10

  function inner() {
    // Inner function has access to `x` from outer scope
    console.log(x)
  }

  return inner
}

// Create a new function by calling `outer`
let innerFunc = outer()

// Call `innerFunc` from outside of its lexical scope
innerFunc() // Output: 10

In the example above, the outer function defines a variable x with a value of 10. The outer function also defines an inner function called inner, which accesses and logs the value of x. The outer function returns the inner function, so that it can be called from outside of its lexical scope.

When we call outer and assign its return value to the innerFunc variable, the innerFunc variable now refers to the inner function. When we call innerFunc, it logs the value of x from the outer scope, even though x is not defined in the scope where innerFunc is called.

This is an example of function closure, where the inner function has access to the lexical scope of the outer function even when it is called from a different scope. In other words, the inner function is a closure because it "closes over" the x variable, retaining access to it even after the outer function has returned. This is what allows the inner function to log the value of x to the console when it is called.

Function Closure in React

Function closure is a commonly used feature in React, as it allows React components to retain access to their state and other resources even when they are rendered in different contexts.

For example, consider the following function component in React:

function MyComponent() {
  const [value, setValue] = useState(0)

  function handleClick() {
    setValue(value + 1)
  }

  return <button onClick={handleClick}>{value}</button>
}

In this code, the handleClick function is a closure because it has access to the value variable, which is defined in the outer scope of the MyComponent function.

When the user clicks on the button, the handleClick function is called, and it updates the value of value by calling the setValue function and passing in the new value for value (which is the current value of value plus 1).

Because handleClick is a closure, it retains access to the value variable even after the MyComponent function has returned, allowing it to update the value of value correctly.

Join the Newsletter