My WordPress Blog
// Example with var
function exampleVar() {
var x = 1;
if (true) {
var x = 2; // This re-declares the variable
console.log(x); // Output: 2
}
console.log(x); // Output: 2
}
exampleVar();
// Example with let
function exampleLet() {
let x = 1;
if (true) {
let x = 2; // This creates a new variable within the block
console.log(x); // Output: 2
}
console.log(x); // Output: 1
}
exampleLet();
// Example with const
function exampleConst() {
const x = { value: 1 };
x.value = 2; // This modifies the object assigned to x
console.log(x.value); // Output: 2
}
exampleConst();