JavaScript variable scoping trickery

I almost fell victim to this over the weekend, so thought I’d share a common JavaScript gotcha. What does the following line do?

var start = stop = null;

Most people will respond, “define a variable called start and a variable called stop and then set them both to null.” That is generally correct, but not specific enough. What actually happens is that a local variable called start is defined and a global variable named stop is defined; both are then set to null. The var operator applies to start, not to stop because stop is part of the initialization (to the right of the equals sign). This code can be rewritten to create two local variables like this:

var start = null, stop = null;

Now, the var operator applies to both start and stop, creating two local variables (the comma indicates another variable being defined). It’s little things like this that make me love JavaScript.

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-book that explains not just concepts, but also real-world uses of promises.

Download the Free E-book!

The community edition of Understanding JavaScript Promises is a free download that arrives in minutes.