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:
varis function-scoped, which means it is accessible within the function it was declared, or globally if not inside a function. - Hoisting: Variables declared with
varare 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
varcan be re-assigned and updated.
Example:
function exampleVar() { console.log(x); // undefined var x = 10; console.log(x); // 10 } exampleVar();
let
- Scope:
letis block-scoped, meaning it is only accessible within the block, statement, or expression where it is used. - Hoisting:
letis hoisted, but unlikevar, it is not initialized. Accessing it before declaration results in a ReferenceError. - Reassignability: Variables declared with
letcan 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,constis block-scoped. - Hoisting:
constis also hoisted but not initialized, similar tolet. - Reassignability: Variables declared with
constcannot 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
varif you need function-scoped variables (rarely recommended). - Use
letfor variables that will change over time and are block-scoped. - Use
constfor variables that should not be reassigned, ensuring immutability for primitive values.

