A brief talk on the difference _javascript skill when defining variables in JavaScript with or without VAR declaration

Source: Internet
Author: User

Some time ago answered a about the definition of variables using the keyword var or not, summed up a review.

1. Variables defined in the scope of a function are local variables, which are defined as global variables without the definition of var.
Use the 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. Under global scope, variables defined with Var cannot be deleted, and variables without var definitions can be deleted. It also shows that the implied global variable is strictly not a real variable, but a property of the global object, because the attribute can be removed by delete, and the variable is not available.

3. Using the var definition variable also promotes the variable declaration, which is
Use the 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 using the variable defined by Var in advance.

4. In ES5 's ' use strict ' mode, if the variable is not defined with the Var, an error occurs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.