3 ms·
Always use "var" to define a variable, unless you know exactly what you are doing. e.g.: var foo = 'bar'; When you don't use "var" the Javascript interprete
by n8agrin 17y ago
Always use "var" to define a variable, unless you know exactly what you are doing. e.g.:
var foo = 'bar';
When you don't use "var" the Javascript interpreter breaks out of the current scope and continues to do so all the way until it hits the final global scope (generally the window object in browsers). If it does not find the variable, it then defines it. If it does find it, it will trample the found variable with the new value. For example:
var foo = 'bar';
function baz() {
foo = 'baz';
}
baz();
// now foo == 'baz';
console.log(foo);
>>'baz'
Google "Javascript var keyword" for more info.
EDIT: I'll add that this functionality, which is part of a general language feature known as a "closure", is incredibly powerful when used successfully, but that's out of the scope of my comment.
- tyrmored 17y agoAlso, "scope" means inside a function, and not inside a control block (e.g. for loops). I would estimate global variables will cause at least 50% of the headaches an intermediate JavaScript developer experiences. It's particularly bad when you're dealing with rows of data, for example. Get in the habit of declaring every variable in the top line of the function concerned before you use it. If you haven't already mastered closures, this will make things a lot easier for you.