Block-level scope for JS

Source: Internet
Author: User

Today brings the summary of block-level scopes in JS you do not know to share:

1) The scope created with the From object is valid only in the with declaration, not the outer scope , and can access the properties of an existing object and add it to an existing object

Code Demo:

         var obj = {             A:1,             B:2,             C:3         };           with (obj) {             a=3;             b=4;             C=5;
d=6; } Console.log (obj); // 3,4,5

2) The catch clause of the Try/catch creates a block-level scope in which the declared variable is valid only within the catch

Code Demo:

        Try {            undefined (); // perform an illegal operation to force an exception to be created         }        catch(err) {            console.log (err); // be able to perform normally         }        Console.log (err); // Referenceerror:err is not defined

3) Let usage: You can bind a variable to any scope in which it resides (usually {...} Internal

Code Demo:

          for (i = 1; i < 5; i++) {             console.log (i); // 1 2 3 4          }         console.log (i); // 5          for (Let j = 1; j < 5; J + +) {             console.log (j); // 1 2 3 4          }         Console.log (j); // referenceerror:j is not defined

Because let creates a block-level scope, external access to the Let declaration of the variable

4)const: can be used to create block scope variables; The value is fixed ( constant ), and any attempt to modify the value will cause an error

Code Demo:

        varFoo =true; if(foo) {varA = 2; Const B= 3;//block scope constants that are contained in the IFA = 3;//Normalb = 4;//ErrorConsole.log (b);//typeerror:invalid assignment to const ' B ' (this shows that its value is constant and cannot be changed after that)} console.log (a);//PConsole.log (b); //referenceerror! ( This exception can prove that the const created block scope)

Block-level scope for JS

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.