Javascript Closure function

Closure function is a part of advanced javascript, It is basically used to access outer function parameters and variables in the inner function so this inner function is called closure function.
the inner function returns into the outer function.

Suppose, you have a outer function start() and declared employeeName variable in this and called this variable into displayEmployeeName() inner function.


function start() {
  var employeeName = 'John'; // employeeName is a local variable created by start function
  function displayEmployeeName() { // displayEmployeeName() is the inner function, a closure
    console.log("Hello "+employeeName); // employeeName variable declared in the parent function
  }
  displayEmployeeName();
}
start();
Output:-
Hello John

Suppose, you have defined x variable value into the outer scope and captured the x variable value into inner scope function getNum()


var x = 5; // declaration in outer scope
function getNum() {
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 5 to console
Output:-
5

Suppose, You change the outer scope variable x value into the inner function scope then the value will be change.


var x = 5; // declaration in outer scope
function getNum() {
x=2;
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 2 to console
Output:-
2