Skip to main content

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)

javascript
var name = 'Tim';

Features:

  • It can be redeclared and reassigned:

    javascript
    var x = 10; var x = 20; // does not cause an error
  • Function scope (ignores {} blocks)

    javascript
    if (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:

    javascript
    console.log(user); // undefined var user = 'Alex';

Using var in modern code is not recommended.


2. let - the modern way for mutable variables

javascript
let age = 25; age = 26; // can be changed

Features:

  • The value can be changed, but it cannot be redeclared in the same block:

    javascript
    let a = 1; // let a = 2; Error
  • Block scope:

    javascript
    if (true) { let x = 10; } console.log(x); // ReferenceError - the variable is not visible outside the block
  • Not accessible before its declaration (unlike var):

    javascript
    console.log(a); // ReferenceError let a = 5;

Use let when the variable's value will change.


3. const - a constant (immutable reference)

javascript
const PI = 3.14;

Features:

  • It cannot be reassigned or redeclared:

    javascript
    const x = 10; x = 20; // TypeError
  • But if it is an object or array, its internal data can be changed:

    javascript
    const user = { name: 'Tim' }; user.name = 'Alex'; // allowed // user = {} cannot reassign the reference itself
  • Block scope - same as let.

Use const by default, and let only if the variable actually needs to change.


Quick comparison:

Featurevarletconst
ScopeFunctionBlockBlock
Can be redeclaredYesNoNo
Can be reassignedYesYesNo
HoistingYes, with value undefinedYes, but cannot be used before declarationYes, but cannot be used before declaration
Modern standardNo, deprecatedYesYes

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.