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.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.