There are 3 keywords you can define variables in JavaScript.
Using
var
function exampleVar() { if (true) { var x = 10; } console.log(x); // Outputs 10 } exampleVar();
Explanation:
Variables declared with
var
are function-scoped, meaning they are accessible throughout the entire function in which they are declared.var
is also hoisted, which means the variable is moved to the top of its scope during the compilation phase, allowing it to be accessed even before its declaration.In the example,
x
is accessible outside theif
block due to function scoping.
Using
let
function exampleLet() { if (true) { let y = 20; } // console.log(y); // Error: y is not defined } exampleLet();
Explanation:
Variables declared with
let
are block-scoped, limiting their accessibility to the block (enclosed by curly braces) in which they are defined.let
is also hoisted but in a way that the variable is not accessible before its declaration. Attempting to access it before the declaration results in aReferenceError
.In the example,
y
is not accessible outside theif
block due to block scoping.
Using const
function exampleConst() {
const z = 30;
// z = 40; // Error: Assignment to constant variable
console.log(z); // Outputs 30
}
exampleConst();
Explanation:
Variables declared with
const
are block-scoped, similar tolet
, butconst
variables cannot be reassigned once they are assigned a value.const
is also hoisted but, likelet
, attempting to access it before the declaration results in aReferenceError
.In the example,
z
cannot be reassigned after its initial assignment, making it a constant value.
conclusion:
In modern JavaScript, it's generally recommended to use let
and const
over var
due to their block-scoping behavior and more predictable behavior. const
is preferred when the variable should not be reassigned, promoting immutability and safer code.