let, const and var

Declaring Variables

Example

Variables are named containers for values. Use const by default and let when the value must change:

const pi = 3.14159;     // cannot be reassigned
let count = 0;          // can be reassigned
count = count + 1;
console.log(pi, count);

Output

3.14159 1

const Cannot Be Reassigned

Example (error)

Reassigning a const is an error:

const city = "Hyderabad";
city = "Pune";

Output

Uncaught TypeError: Assignment to constant variable.

Example (objects)

But const does not freeze objects: their contents can still change:

const user = { name: "Asha" };
user.name = "Asha Rao";     // allowed: same object, new property value
console.log(user);

Output

{ name: 'Asha Rao' }

let vs const vs var

varletconst
Scopefunctionblockblock
Reassignyesyesno
Redeclare in same scopeyesnono
Hoistedyes, as undefinedyes, but unusable until declared (TDZ)same as let

Note: var is the pre-2015 way. Avoid it in new code; you will still meet it in older projects.

Naming Rules

  • Names can contain letters, digits, _ and $, but cannot start with a digit.
  • Reserved words (let, class, return...) cannot be names.
  • Use descriptive camelCase names: totalPrice, not tp.