Explain difference between var, let and const.

javascript

var, let and const keywords are used to declare variables in Javascript. While var is the oldest keyword for declaring variables from its inception, let and const are introduced in ES6.

All three variables differ in the following cases:

  1. Assignment
  • let and var can be reassigned to a new value while const cannot be reassigned.
1
2
3
4
5
6
7
8
9
10
11
12
13
var a = 10;
a = 20;
//output: 20
console.log(a);

let b = 'hello';
b = 'world';
//output: 'world'
console.log(b);

const c = 'hello'
//Error: Uncaught TypeError: Assignment to constant variable.
c = 'world'

This makes const the best option for declaring values that do not change in the program, preventing reassignment.

  1. Scope
  1. Hoisting
  • var is always hoisted to the top of their respective scope.
  • let and const is also hoisted but will throw an error if the variable is used before the declaration. It is a little complicated and we will discuss it in a separate article dedicated to this specific topic.

Related Article

Share and support us

Share on social media and help us reach more people