The scope is the current context of execution in which values or expressions are “visible” or can be referenced. If a variable or expression is not in the current scope, it will not be available for use.
JavaScript has the following kinds of scopes:
Global scope: The default scope for all code running in script mode.
Module scope: The scope for code running in module mode.
Function scope: The scope created with a function.
Block scope: The scope is created with a pair of curly braces (a block).
The var statement declares a function-scoped or globally-scoped variable, while let and const are block-scoped.
Get Amal Mohan K’s stories in your inbox
Join Medium for free to get updates from this writer.
Examples,
Example 1
var x = 1; let y = 1; const z = 1;
if (true) { var x = 2; let y = 2; const z = 2; }
console.log(x); // Expected output: 2 . Since var is global scoped
console.log(y); // Expected output: 1 . Since let is block scoped
console.log(z); // Expected output: 1 . Since const is block scoped
Example 2
if (true) { var a = 10; let b = 20; const c = 30; }
console.log(a); // Expected result: 10. Since var is global scoped
console.log(b); // ReferenceError: b is not defined. Since let is block scoped
console.log(c); // ReferenceError: c is not defined. Since const is block scoped