Ways to declare a variable
JavaScript has three ways to declare a variable: var, let, and const.
They differ in scope, whether they can be redeclared, and hoisting behavior.
Let's go through them in detail.
1. var - the old way (ES5 and earlier)
var name = 'Tim';Features:
-
It can be redeclared and reassigned:
javascriptvar x = 10; var x = 20; // does not cause an error -
Function scope (ignores
{}blocks)javascriptif (true) { var a = 5; } console.log(a); // 5 - the variable "escaped" outside the block -
Hoists - the variable is accessible before its declaration, but its value is
undefined:javascriptconsole.log(user); // undefined var user = 'Alex';
Using
varin modern code is not recommended.
2. let - the modern way for mutable variables
let age = 25;
age = 26; // can be changedFeatures:
-
The value can be changed, but it cannot be redeclared in the same block:
javascriptlet a = 1; // let a = 2; Error -
Block scope:
javascriptif (true) { let x = 10; } console.log(x); // ReferenceError - the variable is not visible outside the block -
Not accessible before its declaration (unlike
var):javascriptconsole.log(a); // ReferenceError let a = 5;
Use
letwhen the variable's value will change.
3. const - a constant (immutable reference)
const PI = 3.14;Features:
-
It cannot be reassigned or redeclared:
javascriptconst x = 10; x = 20; // TypeError -
But if it is an object or array, its internal data can be changed:
javascriptconst user = { name: 'Tim' }; user.name = 'Alex'; // allowed // user = {} cannot reassign the reference itself -
Block scope - same as
let.
Use
constby default, andletonly if the variable actually needs to change.
Quick comparison:
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Can be redeclared | Yes | No | No |
| Can be reassigned | Yes | Yes | No |
| Hoisting | Yes, with value undefined | Yes, but cannot be used before declaration | Yes, but cannot be used before declaration |
| Modern standard | No, deprecated | Yes | Yes |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.