This article mainly introduces the differences and examples of non-var declarations when defining variables in JavaScript, for more information about the differences between using the keyword var when defining variables, let's take a closer look.
1. the variables defined by var in the function scope are local variables, and those defined by var are 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'
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, the variables defined by var cannot be deleted, and the variables without var can be deleted. it means that the implicit global variable is not a real variable, but a global object attribute, because the attribute can be deleted through delete, but the variable cannot.
3. Using var to define a variable also promotes the variable Declaration, that is
Use var to define:
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 ES5's 'use strict 'mode, if the variable is not defined using var, an error is returned.