Difference between var, let and const
const. But there are few rules to create a variable :
- Name can start with _,$, alphabet.
- Names are case-sensitive.
- Names cannot start with a number.
- Reserved words of JavaScipt cannot be used as variable names.
Variables declared using
varare 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.
We can declare variables with
letkeyword 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 .
let for declaring a variable helps where we need to reassign like in for loop or using it as a counter.
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
const it will give Reference error ,
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