views:

76

answers:

3

I am picking up maintenance of a project and reading code:
I see two methods of variable declaration. Can someone explain what the difference between the first and second line means?

To me, I am reading that in javascript, the var keyword is optional. in the first line, they have declared two new variables and initialized them. In the second line, they have declared two new varialbes but not have initialized them. Should I take anything more from this?

aURL = ""; msgNb = 1;
var mode, param, counter;
+9  A: 

Unless all these variables are inside a function they're all globals, the first two are assignments which I would guess because they were previously declared, otherwise it may be shortened to

var aURL = '', 
    msgNb = 1, 
    mode, 
    param, 
    counter;

The unassigned ones have an undefined value by default.

You should always use the var keyword to keep the variable within the same function scope and not force it to become an implicit global, otherwise you could run into issues with duplicate variable naming and assignment.

meder
+3  A: 

If you're not using var then you're using (or creating) a variable from a "parent" scope, all the way up to being global if it doesn't find a local one at any scope.

Greg
+3  A: 

This is not a "jquery" issue per say but rather a JavaScript issue. A variable without the "var" keyword has global scope, i.e., it is visible from all methods, objects, etc... A var is only visible within its specific scope.

Michael