scope of an identifier (variable, function, etc.) = parts of the program where it can be accessed.
Modern JavaScript has four main types of scopes that are mentioned below:
window
object. var todoList = ["grocery", "exercise", "meeting"];
function emptyTodoList() {
todoList = [];
}
console.log(window.hasOwnProperty("todoList"));
// true
console.log(window.hasOwnProperty("emptyTodoList"));
// true
const todoList = ["grocery", "exercise", "meeting"];
let emptyTodoList = function () {
todoList = [];
};
console.log(window.hasOwnProperty("todoList"));
// false
console.log(window.hasOwnProperty("emptyTodoList"));
// false
function printSquare(num) {
result = num * num;
console.log(result);
}
printSquare(9);
console.log("implicit global "+ result)
there is another way we get implicit global variables
value of the id
attribute or the name
attribute of HTML elements also gets added as a variable in the global scope of JavaScript.
<h1 id="mainHeading">Hello World!</h1>
function paramScope(arr=["initial array"], buff=()=>arr) {
var arr = [1, 2, 3];
console.log(arr); // [1, 2, 3]
console.log(buff()); // ["initial array"]
}
paramScope();
var
, scopes collapse
function paramScope(arr=["initial array"], buff=()=> arr) {
arr = [1, 2, 3];
console.log(arr); // [1, 2, 3]
console.log(buff()); // [1, 2, 3]
}
paramScope();
let fn = function namedFn() {
// code ...
};
In the code example above, the name of the function expression namedFn
is only accessible inside the function body.
As a result, some might incorrectly believe that the name of a named function expression is declared inside the function body, but that is not correct; the name is declared in a different scope. The following code proves this claim:
let fn = function namedFn() {
let namedFn = 123;
console.log(namedFn); // 123
};
nameFn
inside the function body is actually shadowing the name of the function expression.scope that exists between blocks of code, such as if blocks or loops.
Prior to the addition of block-scoped let
and const
in the JavaScript language, variables defined with the var
keyword in a block were accessible outside that block.
This is because the variables declared with the var
keyword have function scope.
Different scopes can be nested inside other scopes, creating a chain of scopes. This is known as a scope chain.
process of traversing the scope chain will continue until the global scope is reached and there are no other scopes to look into for the declaration