Javascript scope offset

I studied the concept of variable fields in JS, found this example in it:

(function() {
    var foo = 1;
    function bar() {
        var foo = 2;
    }
    bar();
    console.log(foo) //outputs 1
    if(true) {
        var foo = 3;
    }
    console.log(foo) //outputs 3
})();

output of this function

1 
3

Now I am confused how it happened that it foogets the value 3 in the second log. even when fooannounced using varc if. should the one foodeclared in ifhave a new instance as it falls in bar()??

+4
source share
2 answers

In Javascript, there are only two kinds of scope; scope and global scope.

The code inside the operator ifdoes not have its own scope, so the variable inside the operator ifis the same as the external one.

. var if , ​​ , .


, , , , :

var foo = 1; // a global variable
(function() {
  console.log(foo) //outputs "undefined"
  foo = 2; // sets the local variable
  if(false) {
    var foo = 3; // creates the local variable, but the assignment never happens
  }
  console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1
+3

if ( , langauges). JavaScript function() {} .

+8

Source: https://habr.com/ru/post/1528805/


All Articles