Some time ago, I answered a difference between using the keyword var when defining variables. Let’s review it.
1. The variables defined by adding var to the scope of the function are local variables, and those defined without var become global variables.
Use var to define:
var a = 'hello World';function bb(){ var a = 'hello Bill'; console.log(a); }bb() //'hello Bill'console.log(a); //'hello world'Not using var definition:
var a = 'hello World';function bb(){ a = 'hello Bill'; console.log(a); }bb() //'hello Bill'console.log(a); //'hello Bill'2. Under the global scope, variables defined with var cannot be deleted, variables defined without var can be deleted. This means that implicit global variables are strictly not real variables, but attributes of global objects, because attributes can be deleted through delete, and variables cannot be.
3. Defining variables using var will also improve variable declarations, i.e.
Use var to define:
function hh(){ console.log(a); var a = 'hello world';}hh() //undefinedNot using var definition:
function hh(){ console.log(a); a = 'hello world';}hh() //'a is not defined'This is the declaration of variables defined using var in advance.
4. In ES5's 'use strict' mode, if the variable is not defined using var, an error will be reported.