What is Lexical Scoping in JavaScript?

Please explain Lexical Scoping in JavaScript with an example.

We have described the Lexical Scoping concept very clearly using an example which

everybody can find it very helpful.

function tempFunc() {
  var name = 'Laptop'; // name is a local variable created by tempFunc
  function printName() { // printName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
tempFunc() creates a local variable called name and a function called printName().

The printName() function is an inner function that is defined inside tempFunc() and

is available only within the body of the tempFunc() function. Note that the printName() function

has no local variables of its own. However, since inner functions have access to the

variables of outer functions, printName() can access the variable name declared in

the parent function, tempFunc().


Run the code and notice that the alert() statement within the printName() function successfully

displays the value of the name variable, which is declared in its parent function.

This is an example of lexical scoping, which describes how a parser resolves variable names

when functions are nested. The word lexical refers to the fact that lexical scoping uses the

location where a variable is declared within the source code to determine where that variable

is available. Nested functions have access to variables declared in their outer scope.