Questions on Javascript hoisting

后端 未结 4 472
隐瞒了意图╮
隐瞒了意图╮ 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:17

    Variable declarations get hoisted to the top of every function, but the value assignments stay where they are. So the second example is run like this:

    var me = 1;
    function findme () {
        var me;  // (typeof me === 'undefined') evaluates to true
        if (me) { // evaluates to false, doesn't get executed
            me = 100;
            console.log(me); 
        }
        console.log(me); 
    }
    findme();
    

提交回复
热议问题