1

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.

Gyanesh Gouraw
  • 1,991
  • 4
  • 23
  • 31
  • 1
    See http://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements – elclanrs Mar 07 '16 at 16:43
  • 1
    That's a function expression, and doesn't declare any variable in any scope but its own. You really really should not use that in the condition of an if statement. – Bergi Mar 07 '16 at 16:44
  • @elclanrs: not exactly – Bergi Mar 07 '16 at 16:45
  • Not exactly, you need to declare x first (or later due hoisting) to call it – loadaverage Mar 07 '16 at 16:45
  • function expressions execute immediately, and are scoped to their containing function block, in this case the parenthesis. x is undefined because its out of scope. – Bosworth99 Mar 07 '16 at 16:45
  • 4
    What is this supposed to do anyway? A function literal will always be *truthy*. What are you hoping to test there as condition? – deceze Mar 07 '16 at 16:46
  • like i said it's there to checkout lexical scope system in javascript , nothing to add to functionality as such. – Gyanesh Gouraw Mar 07 '16 at 16:49

1 Answers1

5

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.

deceze
  • 510,633
  • 85
  • 743
  • 889