Variables in JavaScript have two types of scoping i.e. Local and Global scope. If any variable is declared inside a function, then it is a local variable and if the variable is declared outside the function then it is global variable. The scope of variables is defined by their position in the code.

Lexical Scope

JavaScript follows Lexical scoping for functions. Lexical scope means any child’s scope has access to the variables defined in parent’s scope i.e. inner functions can access the global variables.

var a = 5;

function sum() {
  return a + 6;
}
console.log(sum()); // 11

In the above example, function sum() is using global variable "a" to perform the addition. That means variable "a" is in scope of sum().

#closure #lexical-scope #javascript #javascript-tips #web-development

Closures and Lexical Scoping in JavaScript
1.25 GEEK