Updated on 12 Sep 2022 | 3 Min Read
By
 

With JavaScript, the user can declare variables with three keywords, which are let, var, and const. The terms var let and const are somewhat confusing. We will explain all 3 variables with the help of examples.

The difference between the variables var, let as well as const is described below in different ways.

  • Scope
  • Hoisting
  • Reassign the value
  • Redeclaration of the variable

1. Scope

var let const
It's a function scope block scope block scope
Function scope example

const func = () => {
    var val1 = 5;
    if(true) {
        var val2 = 10;
        console.log(val1); //Output 5
        console.log(val2); //Output 10
    }
}
func();
console.log(val1); //undefined. Not available outside function
console.log(val2); //undefined. Not available outside function

Block scope example

const func = () => {
    let x = 10;
    if(x === 10) {
        let y = 20;
        console.log(x); //Output 10
        console.log(y); //Output 20
    }
    console.log(x); // Output 10
    console.log(y); // ’undefined'
}
func();

2. Hoisting

Hoisting is the term used to define a variable prior to its declaration.

var let const
Allowed Not allowed Not allowed
var1 = 100; 
console.log(var1);
var var1;
// 100
let1 = 100; 
console.log(let1);
let let1;
// ReferenceError: let1 is not defined
const1 = 100; 
console.log(const1);
const const1;
// SyntaxError: Missing initializer in const declaration

3. Reassign the value

var let const
Allowed Allowed Not allowed

4. Redeclaration the value

var let const
Allowed Not Allowed Not allowed