What is the difference between var and let and const in JavaScript?
All these keywords are used frequently in application development and used to store the values. Nevertheless, at the high level, these have few common features and few differences. let us see the difference between all with practical examples.
Var in JavaScript
Var is used to declare a variable and the declared variable is used to store the value. it is allowed to hoist the variable, can be reassigned, and redeclare it.
How do you declare a variable?
var customerName = “Raghu coneru”;
or
var customerName;
customerName=”Raghu coneru”;
Hoist: define the variable before the declaration of it.
customerName = “Raghu coneru”;
var customerName;
Note. ES6 suggests using let instead of var.
Let in JavaScript
Let is used to declare the variable and the declared variable is used to store the value. Same as the Var keyword, however, there are a few differences.
- It is the block scope variable. when the variable is declared in the block, this can be only accessible inside the block.
- It is not allowed to Hoist the variable.
- Can be able to reassign the values.
- Cannot redeclare the variables.
- Let it support all modern browsers.
- Let is not support IE.
How to declare a Let?
let customerName = “Raghu coneru”;
or
let customerName;
customerName=”Raghu coneru”;
Const in JavaScript
Const is used to declare the variable and the declared variable is used to store the value. Same as the Var, Let keyword, however, there are a few differences.
- A const variable assigns the values when it is declared. However, in the var and let, it is optional.
- Reassigning the value can’t be possible.
- Redeclare the values can’t be possible.
- It is not allowed to hoist the variable.
Declare the const
Const defalutUsers =[“Raghu” , “Joke” ,”Ivan” ]