Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Nested Functions

All functions have access to the global scope and, in fact, can access the scope “above” them.

JavaScript allows for nested functions, and these inner functions have access to the variables in their enclosing (parent) scope.

In the following example, the inner function plus() can access the counter variable from its parent function.

Example

function add() {
  let counter = 0;
  function plus() {counter += 1;}
  plus();   
  return counter;
}

This could have solved the counter issue, if we could access the plus() function from outside the parent function.

We also need to ensure that counter = 0 is executed only once.

To achieve this, we need to use a closure.