Rojakcoder

Tech and Biz Ramblings

JavaScript Gotcha 1

JavaScript code snippet
From @KyleDavidE

What is the output?

I saw this code snippet from a Tweet reply to Jake Archibald’s tweet.

This is another one of those JavaScript gotchas that I don't think about because it rarely surfaces in my day-to-day code (probably due to the way I write my code), but it shakes the basic understanding of the language's inner workings.

The answer is

1
2

For a detailed explanation, watch this YouTube video from Jake. In short, the value of val is evaluated at the point the statement is encountered. In both the increment statements, the value of val is 0 when they are being evaluated. This is why the values are never added summed up.

comments powered by Disqus

Related contents