JavaScript Scope

September 2, 20205 min read

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.

{
var a = 'a'
let b = 'b'
const c = 'c'
}
console.log(a) // => 'a'
console.log(b) // ReferenceError: b is not defined
console.log(c) //ReferenceError: c is not defined
function scope() {
var insideFunction = 'a'
return insideFunction
}
console.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.

function outerFunction() {
// the outer scope
const outerVar = 'I am from outside!'
function innerFunction() {
// the inner scope
console.log(outerVar) // 'I am from outside!'
}
return innerFunction
}
const inner = outerFunction()
inner()

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.