Hello, as I am not very well versed with javascript, I would like to know the difference between let and var keyword of javascript?(With example if possible)
Or Any reference link with proper details will also work, thanks
let was introduced with ECMAScript 2015.
The let statement declares a block scope local variable, you can initialize it to a value just like var. So the main difference between let and var is, var declares variables globally or locally to entire function regardless of block scope. If you use the let in top of the functions or program, It does not create a global property like var.
For example:
function varExampleFunc(){
var x =1;
if (x === 1){
var y =2;
}
console.log(x);
console.log(y);
}
Output of the above code will be
1
2
As you can see we were still able to print the value of y var which was printed outside the function it was declared it
Now let's create another function like above but using let
function letExampleFunc(){
let x =1;
if (x === 1){
let y =3;
console.log(typeof(y));
}
console.log(x);
console.log(typeof(y));
}
Output
number
1
undefined
as you can see, we were not able to print value of let y which was declared inside function
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly