Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice on Javascript variable initialization [duplicate]

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

var foo = bar = "Some value";
like image 384
adrield Avatar asked Sep 14 '15 14:09

adrield


1 Answers

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;
like image 57
adrield Avatar answered Sep 24 '22 02:09

adrield