Function in if condition clause

孤人 提交于 2019-12-20 05:36:14

问题


I have been given this function to predict the output. It's says refrence error,i am still wondering why?

  if(function x(){console.log("ABC");})
    {
      x();
    }

Hope somebody can throw some light on the lexical scope. Thanks in advance.


回答1:


What you have there is a function expression, even if a named one, and you're not assigning that expression to anything. The fact that you're naming it x doesn't mean a function x will be hoisted in the scope, because that doesn't work for expressions.

function foo() {}    // function declaration
(function bar() {}); // named function expression, the () makes it not-a-statement here

foo();  // ok
bar();  // doesn't exist

So in effect you're never declaring a function x, which is why none exists when you try to call it.



来源:https://stackoverflow.com/questions/35849205/function-in-if-condition-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!