1. var is Functional Scope
{
var a = 5;
}
console.log(a);
// Output:
5
2. let & const is Block Scope
{
let a = 5;
const b = 5;
}
console.log(a, b);
// Output:
ReferenceError: a is not defined
ReferenceError: b is not defined
3. Variable Shadowing of let & const
function test() {
let a = "hello";
if (true) {
let a = "hi";
console.log(a);
}
console.log(a);
}
test();
// Output:
hi
hello
4. Illegal Shadowing of var
While shadowing a variable it should not cross the boundary of scope
Shadowing var by let will work fine, but shadowing let by var wont work.
function test() {
var a = "var";
let b = "let";
if (true) {
let a = "let";
console.log(a);
var b = "var";
console.log(b);
}
}
test();
// Output:
let
Identifier 'b' has already been declared
5. Declaration, Initialization & Re-Initialization
var a;
var a;
// No Error
let a;
let a;
// Identifier 'a' has already been declared
let a;
var a;
// No Error
const a;
// Missing initializer in const declaration
const a = 10;
const a = 6;
// Identifier 'a' has already been declared
var a = 1
a = 2
let b = 1
b = 2
// No Error
const c = 1
c = 2
// Assignment to constant variable
6. Hoisting
There are two phases of JavaScript Execution Context
- Creation phase: In this phase, the JavaScript engine creates the execution context and sets up the scripts environment. It determines the values of variables and functions and sets up the scope chain for the execution context.
- Execution phase: In this phase, the JavaScript engine executes the code in the execution context. It processes any statements or expressions in the script and evaluates any function calls.
Hositing: During Creation Phase JS Engine moves variables and function declartions to the top of code.
var, let, const all will be undefined due to hoisting, but let and const throw reference error due to hoisting in temporal dead zone.
Temporal Dead Zone: Specific period in the execution of JavaScript code where variables declared with let and const exist but cannot be accessed or assigned any value.
TDZ is the time between initialization and execution of variables.
TDZ is the state where variables are in scope but not yet declared.
console.log(a);
var a = 1;
// undefined
console.log(b);
let b = 2;
// ReferenceError: Cannot access 'b' before initialization
console.log(c);
const c = 3;
// ReferenceError: Cannot access 'c' before initialization