Inner Functions

JavaScript functions can be declared inside other functions! Each function creates its scope.

function outer() {
  let a = 1;

  function inner() {
    let a = 2;
    let b = 3;
    console.log(a);
    console.log(b);
  }

  inner();
  console.log(a);
  console.log(b);
}

outer();

The inner functions have access to the variables in their parent function.

function outer() {
  let num = 1;

  function inner() {
    num++;
  }

  console.log(num);
  inner();
  console.log(num);
}

outer();

When one should use inner functions? If a function relies on a few other functions that are not useful to any other part of your code, you can nest those helper functions inside it.