Difference between let, var, and const in JavaScript
Difficulty: Easy, Languages: JS, TS, Author: Kiran Dash (opens in a new tab)
Question
What is the difference between let
, var
, and const
in JavaScript?
Answer
let
, var
, and const
are used to declare variables in JavaScript. The main difference between them is the scope and reassignment of the variable and how they are hoisted in the code
Scope and Reassignment
var
is function-scoped and can be redeclared and reassigned.let
is block-scoped and can be reassigned but not redeclared.const
is block-scoped and cannot be reassigned or redeclared.
Here is an example to demonstrate the difference between let
, var
, and const
showcasing their reassignment and redeclaration properties:
example.js
var a = 10;
let b = 20;
const c = 30;
console.log(a); // 10
console.log(b); // 20
console.log(c); // 30
a = 40;
b = 50;
// c = 60; // Error: Assignment to constant variable.
console.log(a); // 40
console.log(b); // 50
console.log(c); // 30
var a = 70;
// let b = 80; // Error: Identifier 'b' has already been declared
// const c = 90; // Error: Identifier 'c' has already been declared
In the example above, var
can be reassigned, let
can be reassigned but not redeclared, and const
cannot be reassigned or redeclared.
Here is an example to demonstrate the scope of let
, var
, and const
:
example.js
function example() {
if (true) {
var a = 10;
let b = 20;
const c = 30;
}
console.log(a); // 10
// console.log(b); // Error: b is not defined
// console.log(c); // Error: c is not defined
}
Hoisting
var
is hoisted to the top of the function or global scope.let
andconst
are hoisted to the top of the block scope.
example.js
console.log(a); // undefined
var a = 10;
// console.log(b); // Error: Cannot access 'b' before initialization
let b = 20;
// console.log(c); // Error: Cannot access 'c' before initialization
const c = 30;