What is the scope of variables in JavaScript? -


What is the scope of variables in javascript? Do they have the same scope in opposing the function? Or does it also matter? Apart from this, where are they stored globally defined variables?

I think I can do the best you give a bunch of examples to study . Javascript programmers have been practically positioned by how well they understand the scope. It can be very intuitive sometimes.

  1. Globally, the scoppy variable

      var a = 1; // global scope function one () {warning (a); // alerts '1'}  
  2. local area

      var a = 1; Work Two (A) {Warning (A); // warns the given logic, not the global value of '1', // local area works three again () {var a = 3; Warning (a); // Alert '3'}  
  3. Intermediate : There is no such thing as block scope in JavaScript ( ES5; ES6 introduction)

    a.

      var a = 1; Function four () {if (true) {var a = 4; } Warning (A); // Alert '4', 'global value' of 1)  

    b.

      var a = 1; Work one () {if (true) {one = 4; } Warning (A); // warning '1' because 'let' uses keyword block scoping}  
  4. Intermediate : Object properties

      var a = 1; Function five () {this.a = 5; } Alert (new five). A); // Alert '5'  
  5. Advanced : Close

      Var a = 1; Var 6 = (function () {var a = 6; return function () {// Javascript "chloror" means that I use 'A' here, // because it is defined in the function in which I Was defined. Alert (a); // alert '6'};}) ();  
  6. Advanced : Prototype-based scope resolution

      var A = 1; Function seven () {this.a = 7; } // [object] loses prototype.property // [object] in the lookup chain in property. For example ... // will not be accessed because 'A' has been set up in the constructor. Seven.prototype.a = -1; // will reach, even if 'B' is not set in manufacturer Seven.prototype.b = 8; Warning (New Seven.) A); // Alert '7' warning (new seven (b).); // Alert '8'  
  7. Global + Local : An extra complex case < / P>

      var x = 5; (Function () {console.log (x); var x = 10; console.log (x);}) ();  

    It will print 5 and 10 undefined and 10 Since javascript always moves variable declarations (not elementary) at the top of the variables, which makes the code equal to:

      var x = 5; (Function () {var x; console.log (x); x = 10; console.log (x);}) ();  
  8. Hold segment-scoppy variable

      var e = 5; Console.log (e); {Throw 6; } Hold (e) {console.log (e); } Console.log (e);  

    It will print 5 , 6 , 5 . Catch clause e inside the shadow global and local variables but this particular scope is only for the canned variable if you type var f; If you write inside the catch clause, then it is exactly the same as you defined it before or after the try-catch block.


Comments