Var Vs Let
In JavaScript, let and var are used to declare variables, but they have some important differences in terms of scope and hoisting.
➡ var:
Variables declared with var are function-scoped. This means that they are only accessible within the function in which they are defined, and they are hoisted to the top of their containing function or script.
Hoisting means that the variable declaration is moved to the top of the function or script during the compilation phase, but the assignment remains in its original place. This can lead to unexpected behavior.
var variables can also be declared and accessed before they are actually defined in the code.
Example:
function example() { console.log(x); // undefined (hoisted) var x = 5; console.log(x); // 5 } example(); console.log(x); // ReferenceError: x is not defined
let:
Variables declared with let are block-scoped. This means they are only accessible within the block (a block is defined by curly braces) in which they are defined, and they are not hoisted to the top of the function or script.
Variables declared with let are not accessible before the point at which they are declared in the code.
Example:
function example() { console.log(x); // ReferenceError: x is not defined let x = 5; console.log(x); // 5 } example(); console.log(x); // ReferenceError: x is not defined
In modern JavaScript, it’s generally recommended to use let (or const for variables that should not be reassigned) over var.