Skip to content

Difference Between var, let and const keywords in JavaScript

ES2015 introduced two new ways to declare variables, let and const. Var is the old brother of let and const. Both let and const provide better block scoping that var. Const differs from let because the immediate value cannot be changed once it is declared. Let’s see them more in detail..

var

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. It can be declared more than one time in the same project/file. You can re-assign the value of the variable any time.

var age; // declaring a variable using var
age = 10; // assigning value to it
var name = "John"; // declaring and assigning value to a var 

Multiple variables can also be chained in a single statement separated by a comma.

var age = 10, name = "John"; 

Variables with simple mathematical expressions can also be declared.

var sum = 15 + 20 + 5;
console.log(sum); // 40 will be printed.

Re-declaring the variable with a new value is possible.

var num = 10;
var num = 20;

console.log(num) // 20 will be printed.

let

It’s similar to var, the difference is that it has block scope. The scope of let is anything between curly braces { } like: functions, if statement, loops or anything.

You can re-assign the value of the variable any time.

let num = 10;
num = 20;

console.log(num) //Prints 20

You can’t declare the variable more than one time.

let num = 10;
let num = 20;

console.log(num) // SyntaxError: identifier "num" has already been declared.

const

Variables declared with const has block scope like let keyword. The only difference being you can’t re-assign the value of the variable again.

const a = 10, b = 20, flag = true;

const has a thumb-rule that a value should be assigned to it while declaring.

const limit; // SyntaxError: missing initializer

const works differently with arrays and objects. When you’re declaring a new array using const keyword, you can change the value of any element in the array but, you can’t change the value of the entire array as it is. For objects, you can change the value of any property in the object but, you can’t change the value of the whole object and also you can’t add more keys in object.

See also  Detect dark mode in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.