I know that in JavaScript I can define a variable in this way:
menuItems = new Array();
or putting the var before the variable name, so:
var menuItems = new Array();
Exist some difference between these two versions ? What change?
Tnx
I know that in JavaScript I can define a variable in this way:
menuItems = new Array();
or putting the var before the variable name, so:
var menuItems = new Array();
Exist some difference between these two versions ? What change?
Tnx
When you don't use var it goes into the global scope (in browser into the window object, in node into the global object). So your first one is equivalent to window.menuItems = ...
in a browser.
This is not usually good because you are polluting the window object potentially overwriting or leaving menuItems to be overwritten by other code.
In the 2nd case it goes into a variable that exists in the scope of the function that wraps that bit of code and any other functions inside it. So
...
function() {
... bits of code except creation of a function ...
var menuItems = new Array();
... bits of code ...
}
// menuItems is undefined here so whatever you do on something called menuItems here actually acts on a different variable menuItems
http://speakingjs.com/es5/ch16.html is an excellent link if you want to delve into details.