How does JS work with these blocks?

Can someone explain why the following produces 1.2 and the other produces 5? Should they not produce 5?

//produces 1,2
(function () {

    var a = [5];

    function bar() {
        if (!a) {
          var a = [1, 2];
        }
        console.log(a.join());
    }

    bar();

})();

Based on reading some articles about closing JS, I expect both of them to release 5. It seems like not finding an article anywhere that could give some idea of โ€‹โ€‹why the first block produces differently.

//produces 5
(function () {

    var a = [5];

    function bar() {
        if (a) {
          console.log(a.join());
        }
        else {
          console.log([1, 2].join())
        }
    }

    bar();

})();

Thank!

+4
source share
4 answers

Due to javascripts var hoisting , this code:

(function () {
    var a = [5];
    function bar() {
        if (!a) {
          var a = [1, 2];
        }
        console.log(a.join());
    }
    bar();
})();

equivalent to this code:

(function () {
    var a = [5];
    function bar() {
        var a; // a === undefined at this point
        if (!a) {
          a = [1, 2];
        }
        console.log(a.join());
    }
    bar();
})();

So, you can see it areally will falsey(i.e.! A === true) if the if condition is checked

+5

var a = [1, 2]; a = [1, 2]; . @Jaromanda , JavaScript.

+1

X , - var hoisting, , .

2 , , . , โ„– 2

//produces [1,2] now
(function () {

  var a = [5];

  function bar() {
      if (a) {
        console.log(a.join());
      }
      else {
        var a = [1,2];
        console.log(a.join())
      }
  }

  bar();

})();

var , , 5

+1

, .

, var a = [5] , .

, , , "", "".

1at op

function bar(){
    if(!a) { 
           var a = [1,2];
          }
    console.log(a);
    }
>> 1,2

1,2. , if a, undefined, ! a true.

? . ? , : , "" , - .

! ? "" - ! A false - , a , . , ,

if (! a [false]), true , a var, .

. .

, if , , :

 function bar(){
    if(a) { 
           var a = [1,2];
          }
    console.log(a);
    }
>> undefined

[! , if (!! a)] , , , , "a" [1,2];

?! if, a, , : " " bar.

- - . - , , .

a undefined.

This was unexpected; contradictory; defiantly, but apparently correct! This is correct because the local variable a was initialized, but did not start entering the value correctly. We tried to re-declare one of the higher context, and this was forbidden.

The only good thing is that the behavior looks uniform in browsers.

-2
source

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


All Articles