JS even the trap of assigning value

Source: Internet
Author: User

  

Take a look at the code first:

(function() {    var x = y = 1;}) (); Console.log (y); Console.log (x) ;

At first, I thought the problem was just a split question, and it was obvious that the result was, y=1;x=1

  

Then when I'm out of the console, I feel a loud slap, and the output:

  

  Conclusion: The above results are due to variable elevation and even assignment .

  Analysis: the above var X=y=1 easy to understand as Var x=y,var y=1; Because here the use of even equal assignment, even the operator assignment is from right to left, equivalent to Y=1; var x =y;

And then because of the variable promotion, will all the declaration ahead of time (just declaration ahead, assignment is not advanced) to the top of the function body, var x=y=1, the actual equivalent ofvar A; y=1; var x=y;

     So the above code Console.log (y) has a value of 1 because Y=1 is not declared inside the function body with Var, so it is not a local variable, it is a global variable.

     Note: ① variables that are not declared with VAR are global variables; ② declares the variable with Var, but outside the function body, there is no global variable in the function body.

A variable that is ③ in the function body but not declared with VAR is also a global variable, and the variable declared with VAR is the local variable ④ in the function body.

The ⑤ variable promotion is only declared forward to the top of the function body, and the assignment does not advance

     Perhaps you will ask, that Console.log (x) above why not output undefined, but error?

Calling a variable that is not declared in the scope will cause an error. A variable is undefined only if it is declared but not assigned. Here the variable x is not declared in the global scope, does not exist, so will error!

Therefore, it is suggested that we should try not to use even such assignment, there will be many hidden dangers

  

  

JS even the trap of assigning value

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.