Block and shadowing in javascript
Block
Referring to is grouping multiple statements together inside a block (curly braces {}
) in JavaScript.
This is often done when JavaScript expects a single statement but you want to execute multiple statements in that context
Example:
if (true) {
let a = 10; // First statement
console.log(a); // Second statement
}
Explanation:
The
if (true)
statement expects a single statement to execute if the condition istrue
.By wrapping multiple statements inside the curly braces
{}
, we create a block of code.Inside the block:
The first statement,
let a = 10;
, initializes the variablea
.The second statement,
console.log(a);
, prints the value ofa
to the console.
Without the curly braces, only the first statement (the one immediately following the if
) would be executed conditionally. Any subsequent statements outside the braces would run regardless of the if
condition.
Shadowing:
Shadowing happens when a variable declared in a inner scope (like within a block) has the same name as a variable in an outer scope.
var does not create a new block-scoped variable, it modifies the variable in the outer scope (if declared in the global scope, it changes the global one).
let and const are block-scoped, meaning they don't overwrite the variable in the outer scope.
example
var a = 100;
{
var a = 10;
let b = 20;
const c = 30;
console.log(a);
}
console.log(a);
The first console.log(a) inside the block prints 10, because the global a is shadowed within the block by the var a = 10;.
The second console.log(a) outside the block prints 10 as well, because var has affected the global a and it was overwritten by the value 10 inside the block.