4

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

var foo = bar = "Some value";
1
  • You may get "scoping problems", have a look at Issues with this approach for detailed explaination Commented Sep 14, 2015 at 14:42

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

2 Comments

... or var posX = 0, posY = posX;
@Pointy nice, concise alternative!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.