Articles in the Var keyword in javascript

Source: Internet
Author: User

It is perfectly legal for JavaScript to ignore the VAR keyword when declaring a variable. JavaScript, as a weakly typed (loosely-typed) language, does not declare the variable type to be understandable, but the fact is not so straightforward, because the properties of a variable are scoped beyond the type. The following examples illustrate:

the

<script language= "JavaScript" >var a = 0;document.write (A + ' <br> '); var b = 1;function foo () {document.write (b + ' <br> ');d ocument.write (window.b); var b = 1;} Foo ();</script>
Results show:

0
Undefined
1

Note: variable elevation hoisting: Before execution, the code is loaded into memory, and the declaration of a variable in function is "lifted" to the front of the function, with the other order unchanged. However, in the actual development is not advocated written in the back, the above funtion equivalent to:

<script language= "JavaScript" >var a = 0;document.write (A + ' <br> '); var b = 1;function foo () {var bdocument.wri Te (b + ' <br> ');d ocument.write (window.b); = 1;} Foo ();</script>

No.2
<script language= "JavaScript" > A = 0;document.write (A + ' <br> '); b = 1;function foo () {document.write (b + ' <br> ');d ocument.write (window.b+ ' <br> '); b = 2;document.write (+ + ' & Lt;br> ');d ocument.write (window.b);} Foo ();</script>

Results show:

0
1
1
2
2

Summary: Var declares a local variable (extension: scope), and without Var, the variable defaults to global.

Articles in the Var keyword in javascript

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.