Using the keyword var
ensures that your variable is properly scoped. If you do not use the keyword, then JavaScript will automatically create the variable as a global scope, which can cause issues later in the execution of your page.
name = 'Bic'; // implicitly global
function myFunc() {
var name = 'John'; // this variable is scoped here
console.log(name); // John
getName(); // Bic
}
function getName() {
console.log(name); //Bic
}
myFunc();
getName();
In the code above, I declared a global name, and a scoped name. Note, the global name lingers on after myFunc() has finished executing. name
is a property of most HTML elements. In this particular answer, my declaration of name without the var
keyword can have detrimental affects to a page's execution. The value of name
gets thrown out of scope, and this can affect targeting elements, and other things. If you take a look at this Fiddle, and click Run again after it loads, you will notice it automatically opens a new tab. This is because the original value of name has been clobbered, and the page does not know where to truly open.
As a general rule, it is good to always declare variables with the var
keyword, as this makes it easier to follow the scope of that variable, as avoids unforeseen issues they can cause.
As was noted by Pointy, the 'use strict' pragma (introduced in ECMAScript 5) actually prohibits the declaration of variables without the var
keyword.