Variables for JavaScript functions

Source: Internet
Author: User

Several special cases of function internal variables:

1. Global variables and local variables

function internal variable declaration with var keyword:

1 function Global () {2      var name = "Lilei"  //variable declaration with VAR, still local variable, external 3}4Global () is not found; 5 Console.log (name)//Cannot Print

The function internal variable declaration does not have the var keyword:

1 function Global () {2     name = "Lilei"//is at this time global variable 3}4Global (); 5 Console.log (name)//' Lilei '

2. function internal variable Promotion

1 function Test () {2    console.log (v); 3     var v = 1; 4 }5//undefined

The above code is equivalent to

1 function Test () {2     var v = undefined; 3     Console.log (v); 4     V =1; 5         }6 test ()//undefiend

Note: The variable declaration is promoted to the top of the function, but the variable is assigned to the original position

3. Combination of function scope and variable declaration promotion

var name = ' Nelsen 'function  Global () {    console.log (name)}global ();//' Nelsen '

The function does not declare the name, nor is it initialized, when the function finds the global scope along the scope chain to see if there is a variable declaration with the same name, and then returns the initialized value.

1 var name = ' Nelsen '; 2 function Global () {3    console.log (name)4     var  name; 5 }6 Global (); Undefined

The function outside declares name and initializes it, and the function internally declares name, and returns the default undefined

Variables for JavaScript functions

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.