JavaScript Scope

September 2, 2020

The scope is at the base closure. Scope manages the availability and lifetime of the variables and parameters and defines the idea of a global and local variable. In other words, the scope is an encapsulation mechanism for code blocks, functions, and modules. ES6 and CommonJS modules also create a scope unless the variable is explicitly exported from these modules. Scopes can be nested, and we can use the terms "outer" and "inner" scope for nesting. The inner scope can access the variable of its outer scope. The variables declared inside the global scope are called "global variables" and can be accessed from any scope. Browser supplies window and document global variables. Code block does not create scope for var variables; only the function body does.

index.js
1{
2 var a = 'a'
3 let b = 'b'
4 const c = 'c'
5}
6
7console.log(a) // => 'a'
8console.log(b) // ReferenceError: b is not defined
9console.log(c) //ReferenceError: c is not defined
10
11function scope() {
12 var insideFunction = 'a'
13 return insideFunction
14}
15
16console.log(insideFunction) // ReferenceError: insideFunction is not defined

Static scoping (lexical scoping) - means that the "inner" scope can access the variable of its outer scope. The variables' accessibility is determined statically by the variables' position within the nested function scope and consists of outer scopes.

index.js
1function outerFunction() {
2 // the outer scope
3 const outerVar = 'I am from outside!'
4
5 function innerFunction() {
6 // the inner scope
7 console.log(outerVar) // 'I am from outside!'
8 }
9
10 return innerFunction
11}
12
13const inner = outerFunction()
14inner()

Closures are essential to the programmer because they can reduce naming collisions and provide automatic memory management. Some programming languages with C syntax have block scope (a list of statements wrapped with curly braces), so variables defined in a block are not accessible from the outside. JavaScript has a block syntax, but it does not have block scope (let and const are block-scoped). JavaScript does have function scope, which means that the variables and parameters defined in a function are not accessible outside of the function. A variable defined within a function is accessible everywhere within that function. The variables defined in a function can be released when the function execution is finished.

Share this post on Twitter