Questions on Javascript hoisting

后端 未结 4 473
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 08:12

While I was reading about Javascript hoisting, I tried the following. I am not sure why the first one and second one output differently. Thanks in advance. (I am not even su

4条回答
  •  天涯浪人
    2020-11-27 09:03

    Hoisting of a var does NOT hoist the assignment, just the declaration. So it's being parsed like this:

    function findme(){
      var me;
      if(me){
        me = 100;
        console.log(me); 
      }
      console.log(me); 
    }
    

    When the if statement runs, me is decalred local to the function, but is undefined (has no value). undefined is falsy so your condition is never true.

    This is why it's customary to always declare your local variables at the top of functions, because that's where they go anyway, if you like it or not.

提交回复
热议问题