Home  >  Article  >  Web Front-end  >  A brief discussion on the difference between defining variables in JavaScript with or without var declaration_javascript skills

A brief discussion on the difference between defining variables in JavaScript with or without var declaration_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:39:121034browse

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn