DEV Community

Lukas Polak
Lukas Polak

Posted on • Updated on • Originally published at lukaspolak.com

JavaScript scope

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.

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.

Closures are an essential service to the programmer because they can reduce naming collisions and provides 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. JavaScript does have function scope, which means that the variables and parameters defined in a function are not accessible outside of the function, and 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.

Top comments (0)