let became available with EcmaScript 2015. Let is introduced as new var. God knows how many times I heard that var is dead... don't use it.... It's bad.... But I was using it last month, and it was working just fine, what happened? I am not here to tell you the same story and give you another lecture. If you know how to use the var, if you are comfortable using it, use it. I like to introduce you let as new alternative of var.
Let Statement
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. Let's look at the examples to understand the differences.
function varExample(){ var x =1; if (x === 1){ var y =2; } console.log(x); console.log(y); }
> 1 > 2
function letExample(){ let x =1; if (x === 1){ let y =3; console.log(typeof(y)); } console.log(x); console.log(typeof(y)); }
> 1 > "number"
> 1
> "undefined"
No comments:
Post a Comment