Assign multiple variables to the same value in Javascript?

I have initialized several variables in the global scope in a JavaScript file:

var moveUp, moveDown, moveLeft, moveRight;
var mouseDown, touchDown;

I need to set all of these variables to false. This is the code I currently have:

moveUp    = false;
moveDown  = false;
moveLeft  = false;
moveRight = false
mouseDown = false;
touchDown = false;

Is there any way that I can set all of these variables to the same value in one line of code, or is the code I currently have the best way to do this?


Solution 1:

Nothing stops you from doing

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

var a, b, c;
a = b = c = 10;
console.log(a + b + c)

Solution 2:

Nothing stops you from doing the above, but hold up!

There are some gotchas. Assignment in Javascript is from right to left so when you write:

var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

it effectively translates to:

var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));

which effectively translates to:

var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));

Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.

Note: My above example assumes you are running your code in the browser, hence window. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global which is the global context for that environment).

Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.

var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.


Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.