Zartab Nakhwa (Code With Z)
3 min readJan 3, 2023

Var vs let vs const in JavaScript

When a variable is declared using var keyword, it becomes a function scoped variable, meaning irrespective of the blocks it can be used anywhere in the function ( you will understand the blocks thing in a while now). So let say you declare a variable using var keyword inside a for loop which is inside a function, in regular circumstances once the for loop ends the variable will no longer be accessible but as you have declared a variable using var keyword it will be accessible.

function sayHello() { 
for (var i = 0; i < 5; i++) {
console.log("Inside the for: ", i);
}
console.log("After the for loop: ", i);
}

sayHello();

Not only that the variables declared using var keyword can also be re-declared and it doesn’t cause any errors.

var name = 'CodeWithZ'; 
var name = "Test";
var counter = 5;
if (counter > 4) {
var name = "CodeWithZ Inc";
}
console.log(name);

This code block will give you an output of CodeWithZ Inc

Then with ES6 enters let and const keywords which resolves the above issues and make the JavaScript variables act normally.

let and const both are block scoped and not function scoped, so unlike above scenario once a variable is defined we won’t be able to use it outside the block as you can see in the code block below.

function sayHi() {
for (let i = 0; i < 5; i++) {
console.log("Inside the for: ", i);
}
console.log("After the for loop: ", i);
}
sayHi();

As we are using a let variable after the scope it will result in an error.

One more visible difference in let and const vs var is that, variable once declared using let or const cannot be re-declared in the same block. Any attempt to do same will result in an error.

One more visible difference in let and const vs var is that, variable once declared using let or const cannot be re-declared in the same block. Any attempt to do same will result in an error.

And one of the major difference between let and const is

Variable declared using let is allowed to change its value whereas variable declared using const cannot change the value which is originally assigned to it.

const someValue = "Test Value"; 
someValue = "Hello";

Following table will help you understand the difference between let and const vs var.

Originally published at https://codewithz.com.