Is it ok in Javascript to declare multiple variables as below?
var foo = bar = "Some value";
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With