Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let var or var to let

In the last couple of months, I've been learning a lot about JavaScript. Having abused the languages for years, I dare say that I now have a better understanding of the language and I've come to love the benefits of its functional nature.
Lately I've taken up learning Scheme, but that's just for fun. Browsing the MDN reference I noticed that JS, though lacking block scope, does have a keyword that can be used to declare a variable local to a given block, much like Scheme's let:

for (var i=0;i<someArray.length;i++)
{
    console.log(someArray[i]);
}
console.log(i);//will log someArray's length

Whereas:

for (let i=0;i<someArray.length;i++)
{
    console.log(someArray[i]);
}
console.log(i);//undefined

So what I want to know now is: Why isn't let used more often? Has it got something to do with X-browser support? Is it just one of those lesser-known-goodies?
In short, what are the advantages of using var over let, what are the caveats?

As far as I can tell, the behaviour of let is, if anything, more consistent (double declarations in a single block raise a TypeError, except for function bodies (ECMA6 drafts fix this, though).
To be honest, apart from this feature/keyword not being very well known, I struggle to think of any argument against using let for loops, or anywhere where a temporary variable makes for more readable code.

like image 513
Elias Van Ootegem Avatar asked Nov 26 '12 15:11

Elias Van Ootegem


People also ask

Is it better to use LET than VAR?

This is because both instances are treated as different variables since they have different scopes. This fact makes let a better choice than var . When using let , you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.

Why would you chose let over var const over Let?

If I don't need to reassign, `const` is my default choice over `let` because I want the usage to be as clear as possible in the code. I use `let` when I need to reassign a variable. Because I use one variable to represent one thing, the use case for `let` tends to be for loops or mathematical algorithms.

Is Let safer than VAR?

Let and const are both safer than var—there's no way to accidentally declare a global variable.


1 Answers

Yes, it has entirely to do with browser support. Currently only Firefox implements it (since it's part of their superset of ECMAScript).

But it is coming in ES6, so there's hope...

I doubt it could be said that there are many benefits to var over let given that both are supported. I think the mantra is going to be "let is the new var"

like image 67
I Hate Lazy Avatar answered Oct 30 '22 01:10

I Hate Lazy