Explain the concept of scope in JavaScript
TL;DR
In JavaScript, scope determines the accessibility of variables and functions at different parts of the code. There are three main types of scope: global scope, function scope, and block scope. Global scope means the variable is accessible everywhere in the code. Function scope means the variable is accessible only within the function it is declared. Block scope, introduced with ES6, means the variable is accessible only within the block (e.g., within curly braces {}
) it is declared.
Scope in JavaScript
Global scope
Variables declared outside any function or block have global scope. They are accessible from anywhere in the code.
Function scope
Variables declared within a function are in function scope. They are accessible only within that function.
Block scope
Variables declared with let
or const
within a block (e.g., within curly braces {}
) have block scope. They are accessible only within that block.
Lexical scope
JavaScript uses lexical scoping, meaning that the scope of a variable is determined by its location within the source code. Nested functions have access to variables declared in their outer scope.