2016-10-20

Javascript 'wat' moments

The new 'let' (ES2015) brings some interesting questions.

Since it makes the variable limited to the scope where it was declared, as opposed to the 'var' which puts the variable in the function scope, what happens when we refer to it from within a lambda function reference?

Check out this JsFiddle for an illustration of the question.

What do you think you're going to see?

The first function block doesn't surprise me. The variable is not evaluated until the lambda function is executed.

For the second function block, I, for one, was expecting some 'Undefined reference' errors on line 18.

Then I executed it. wat? I concluded that the Javascript gods decided to add one more black magic and detect that the variable would not exist when the lambda function would execute.

A friend tried to convince me that I was wrong and that actually a copy was being made for the 'let', so we wrote the third function block. WAT? I certainly wasn't expecting that.

wat?

No comments:

Post a Comment