Javascript Variable Initialization Tips

Is it possible to declare several variables in Javascript as shown below?

var foo = bar = "Some value"; 
+5
source share
1 answer

If you do not know that you are creating a global variable (which in most cases is considered bad practice, anyway), this is not normal.

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

 int foo = bar = 0; 

Both foo and bar will be initialized to 0, as inside the current scope. But in Javascript:

 var foo = bar = 0; 

Creates the foo variable inside the current scope and the bar global variable.


Problem

I debugged the game that I write for about an hour before I realized my mistake. I had code like:

 function Player() { var posX = posY = 0; } function Bullet() { var posX = posY = 0; } var player = new Player; var bullet = new Bullet; 

The variable posY is global. Any method on one object that changes the value of posY will also change it for another object.

What happened: every time a bullet object moved vertically across the screen (changing what it should have been its own posY), the playerโ€™s object was teleported to the Y bullet coordinate.

Solved by simply dividing the variable declaration by:

 var posX = 0; var posY = 0; 
+5
source

All Articles