The difference between let and var in JavaScript
There is a lot of confusion in using the let and var keyword to declare the variables in JavaScript. Let me explain it. Both are used to declare the variable in Javascript where let provide the privilege to declare the variable for a particular block scope and the scope of the variable is limited to it and var used to declare the variable regardless of the block scope.
Below are the differences
Global window object
As both are used to defined variable globally but the variable declared using let will not be available in the global window object
var varnew = “The programmer first”;
let letname = “The programmer first”;
both are declared globally. Let see what is the output when accessing the varialbes in global window object;
console.log(window.varnew);
The programmer first.
Console.log(window.letnew);
undefined
The let varialbe cann’t be accessed in window object and the var can be accessed in the global window object.
Redeclaration
using strict mode var keyword variables allow you to redeclare the varialbe using different values. Where in let will not allow you to redeclare.
‘use strict’
var newval = “The programmer first”;
newval // The programmer first
var newval = “I successfully redeclared”;
newval // I successfully redeclared.
‘use strict’
let newlet = “The programmer first”;
newlet // The programmer first
let newlet = “redeclaring”;
newlet // showing error newlet is already declared
Block
let varialbes are block specific where it can be accessed only for the perticular block and cann’t be accessed outside of the block. Which is used to limit the scope of the varialbe for the perticular block.
Example using for, while loop
//var
for(var i = 0;i<5;i++)
{
console.log(i); // which will display 0 to 4
}
console.log(i); // i is visilble outside of the block and it will display the value 5
//let
for(let j = 0;j<10;j++)
{
console.log(j); // which will diplay 0 to 9
}
console.log(j) // j is not accsilble which will throw reference error saying its not defined
if you delcare var i in for loop which can be accessed outside the for loop which will display 5 once the loop executed. Where using let it cann’t be accessed outside the loop it will throw and reference error saying its not defined.
Function block
let and var works the same way in funtion block.
Here is the example.
//var
function myfun()
{
var myvar = “Difference between let and var”;
let mylet = “Javascipt variable declaration using let and var”;
console.log(myvar); //Difference between let and var
console.log(let); //Javascript varialbe declaration using let and var
}
console.log(myvar); //ReferenceError saying myvar is not defined
console.log(let); //ReferenceError saying mylet is not defined
Both are not accessible outside ot the function block. It scope started and eneded in the function block.
The above examples I m exected using the
jsconsole and chrome browser console. you can also use the same to validate it.