In JavaScript, the keywords let
, const
, and var
are used to declare variables, but they have different behaviors in terms of scope, hoisting, and reassignability.
var
- Scope:
var
is function-scoped, which means it is accessible within the function it was declared, or globally if not inside a function. - Hoisting: Variables declared with
var
are hoisted to the top of their current scope. This means the declaration is moved to the top, but not the initialization. - Reassignability: Variables declared with
var
can be re-assigned and updated.
Example:
function exampleVar() { console.log(x); // undefined var x = 10; console.log(x); // 10 } exampleVar();
let
- Scope:
let
is block-scoped, meaning it is only accessible within the block, statement, or expression where it is used. - Hoisting:
let
is hoisted, but unlikevar
, it is not initialized. Accessing it before declaration results in a ReferenceError. - Reassignability: Variables declared with
let
can be re-assigned.
Example:
function exampleLet() { if (true) { let y = 20; console.log(y); // 20 } console.log(y); // ReferenceError: y is not defined } exampleLet();
const
- Scope: Similar to
let
,const
is block-scoped. - Hoisting:
const
is also hoisted but not initialized, similar tolet
. - Reassignability: Variables declared with
const
cannot be re-assigned. However, if the variable is an object or an array, the properties or elements can be modified.
Example:
function exampleConst() { const z = 30; console.log(z); // 30 // z = 40; // TypeError: Assignment to constant variable. const arr = [1, 2, 3]; arr.push(4); console.log(arr); // [1, 2, 3, 4] } exampleConst();
Summary
- Use
var
if you need function-scoped variables (rarely recommended). - Use
let
for variables that will change over time and are block-scoped. - Use
const
for variables that should not be reassigned, ensuring immutability for primitive values.