Understanding the Differences Between JavaScript's var, let, and const

Manthan Ankolekar - Nov 25 '22 - - Dev Community
var let const
global scoped yes no no
function scoped yes yes yes
block scoped no yes yes
can reassignable yes yes no
can be redeclarable yes no no
can be hoisted yes no no

Global Scoped :

Variables declared Globally (outside any function).

//var
a = 4;
var a;
console.log(a);

//let
a = 4;
let a;
console.log(a); // Uncaught ReferenceError: Cannot access 'a' before initialization

//const
a = 4;
const a;
console.log(a); // Uncaught SyntaxError: Missing initializer in const declaration
Enter fullscreen mode Exit fullscreen mode

Function Scoped :

Variables defined inside a function are not accessible (visible) from outside the function.

//var
function myFunction() {
    var a = 10;
}
myFunction()
console.log(a);

//let
function myFunction() {
    let a = 10;
}
myFunction()
console.log(a);

//const
function myFunction() {
    const a = 10;
}
myFunction()
console.log(a);
Enter fullscreen mode Exit fullscreen mode

Block Scoped :

This scope restricts the variable that is declared inside a specific block, from access by the outside of the block.

//var
function myFunction () {
    if(true) {
        var a = 10; // it exists in function scope
    }
    console.log(a);
}
myFunction();

//let
function myFunction () {
    if(true) {
        let a = 10; // it exists in block scope
    }
    console.log(a);
}
myFunction();

//const
function myFunction () {
    if(true) {
        const a = 10; // it exists in block scope
    }
    console.log(a);
}
myFunction();
Enter fullscreen mode Exit fullscreen mode

Can be reassignable :

//var
var a = 1;
a = 30;
console.log(a); // 30

//let
let b = 1;
b = 30;
console.log(b); // 30

//const
const c = 1;
c = 30;
console.log(c); // Uncaught TypeError: Assignment to constant variable.

Enter fullscreen mode Exit fullscreen mode

Can be redeclarable :

//var
var a = 10;
console.log(a); // 10
var a = 12;
console.log(a); // 12

//let
let b = 10;
console.log(b); // 10
let b = 12;
console.log(b); // Uncaught SyntaxError: Identifier 'b' has already been declared

//const
const c = 10;
console.log(c); // 10
const c = 12;
console.log(c); // Uncaught SyntaxError: Identifier 'c' has already been declared
Enter fullscreen mode Exit fullscreen mode

Can be hoisted :

//var
console.log(a);
var a = 10; // undefined

//let
console.log(b);
let b = 10; // Uncaught ReferenceError: b is not defined

//const
console.log(c);
const c = 10; // Uncaught ReferenceError: c is not defined
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .