Analytics Vidhya
Published in

Analytics Vidhya

Difference between var, let and const

In javascript, we can create variables with let, var and const. But there are few rules to create a variable :

  1. Name can start with _,$, alphabet.
  2. Names are case-sensitive.
  3. Names cannot start with a number.
  4. Reserved words of JavaScipt cannot be used as variable names.

var

Variables declared using var are created before any code is executed in a process known as hoisting. Their initial value is undefined

The scope of a variable declared with var keyword can have either Local Scope or Global Scope.

Function Scope Variable- Variables that can be accessed only in the function, not outside the function are called function scope variable.

Global Scope Variable- Variable that can be accessed globally in code are called global scope variable

We will understand var keyword with the below example, we have an array of principal and calculating simple interest.

As variables are declared with var keyword, they can be accessed outside the function . Here the value of i, SI, and total are 3,12,312 respectively.

But the result will change when we declare the variables with let and const.

let

We can declare variables with let keyword which provide a block scope to the variable whereas var keyword can’t provide the block scope to variables.

In the above example, we will now declare variables with letinstead of var:

As in a scripting language, execution of code will be line by line, we will be getting an error (ReferenceError: i is not define) as variables declared with let keyword have only blocked scope and i is getting print outside the for loop.

When variables declared with var and accessed before declaring will give undefined but when it declared with let and accessed before will give ReferenceError: variable is not defined .

Using let for declaring a variable helps where we need to reassign like in for loop or using it as a counter.

const

Variables can declared with const keyword same like let but variables assigned with const keyword can’t be reassign.

Here lastname value is “Bhatia” which is declared with const . At line 5 again the same variable is assigned to “Kohli” but it throws an error( TypeError: Assignment to constant variable) because with constwe can’t reassign the values.

We can conclude, if variables try to access prior to declaring with var keyword then output will be undefined but with let and const it will give Reference error , var and let can be reassigned but variables declared with const can’t be reassigned.

I hope you are cleared with differences between var, let and const for any queries you can reach me on LinkedIn

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store