Jul 28, 2024
Scope
Scope refers to the visibility of variables in different parts of the code.
Types of scopes:
Example of var:
var a = 5;
console.log(a); // 5
Example of let:
{
let b = 10;
}
console.log(b); // ReferenceError
Example of const:
{
const c = 15;
}
console.log(c); // ReferenceError
Variable Shadowing
Refers to when a variable in a certain scope has the same name as another variable in an outer scope.
Example:
var hello = 'Hello';
{
let hello = 'Hi';
console.log(hello); // High
}
console.log(hello); // Hello
Note: Cannot shadow let or const with var (illegal shadowing).
Declaration
var a = 1;
var a = 2; // No error
let b = 1;
let b = 2; // Error
const c = 1;
const c = 2; // Error
Initialization
Hoisting
console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 10;