DEV Community

Cover image for Explain the difference between var, let and const.
Srijan
Srijan

Posted on • Originally published at hackinbits.com

Explain the difference between var, let and const.

This post first appeared on hackinbits.com

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.

Variables declared using three keywords differ in the following cases:

Assignment

  • let and var can be reassigned to a new value while const cannot be reassigned.
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'
Enter fullscreen mode Exit fullscreen mode

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

Scope

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.

Top comments (0)