5

Is it ok in Javascript to declare multiple variables as below?

var foo = bar = "Some value";
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
adrield
  • 629
  • 6
  • 19
  • You may get "scoping problems", have a look at [Issues with this approach](http://stackoverflow.com/questions/1758576/multiple-left-hand-assignment-with-javascript) for detailed explaination – G-- Sep 14 '15 at 14:42

1 Answers1

5

Unless you are aware that you are creating a global variable (which is mostly considered bad practice, anyway), it's not ok.

If you came from a language like Java, it's natural to do something like:

int foo = bar = 0;

Both variables foo and bar will be initialized with value 0, both inside the current scope. But in Javascript:

var foo = bar = 0;

Will create the variable foo inside the current scope and a global variable bar.


The problem

I was debugging on a game I'm writing for about an hour, before understanding my mistake. I had a code like:

function Player() {
    var posX = posY = 0;
}

function Bullet() {
    var posX = posY = 0;
}

var player = new Player;
var bullet = new Bullet;

Variable posY is global. Any method on one object that changes the value of posY will also change it for the other object.

What happened: every time a bullet object moved through the screen vertically (changing what it should be it's own posY), the player object would be teleported to bullet's Y coordinate.

Solved by simply separating the variable declaration to:

var posX = 0;
var posY = 0;
adrield
  • 629
  • 6
  • 19