Some time ago, I answered a question about the difference between using the keyword var when defining variables or not. Let me summarize it.
1. In the function scope, variables defined with var are local variables, and variables defined without var become global variables.
Use var definition:
var a = 'hello World'; function bb(){ var a = 'hello Bill'; console.log(a); } bb() //'hello Bill' console.log(a); //'hello world'
Do not use var definition:
var a = 'hello World'; function bb(){ a = 'hello Bill'; console.log(a); } bb() //'hello Bill' console.log(a); //'hello Bill'
2. In the global scope, variables defined using var cannot be deleted, and variables defined without var can be deleted. This means that implicit global variables are not strictly speaking real variables, but attributes of the global object. Because attributes can be deleted through delete, but variables cannot.
3. Using var to define a variable will also promote the variable declaration, that is,
Use var definition:
function hh(){ console.log(a); var a = 'hello world'; } hh() //undefined
Do not use 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 the 'use strict' mode of ES5, if the variable is not defined using var, an error will be reported.