Home > OS >  Why does this code output undefined and then raise a TypeError?
Why does this code output undefined and then raise a TypeError?

Time:07-20

function foo() {
  if (true) {
    function bar() { 
      console.log("bar");
    }
  } else {
    function qux() { 
      console.log("qux"); 
    }
  }
  
  console.log(qux); 
  qux(); 
}

foo();
undefined
TypeError: qux is not a function

I don't understand the output of this code. Why does console.log(qux) log undefined? Why do I not get Uncaught ReferenceError: qux is not defined on the console.log instead?

When functions declarations are hoisted, are they not defined or are they initialized to a value of undefined?

CodePudding user response:

The function qux is never defined as the if statement never reaches the else condition.

Modifying your code to the following will solve the problem. There is no need to conditionally (use an if statement) to define a function.

function foo() {
  function bar() { 
    console.log("bar");
  }
  function qux() { 
    console.log("qux"); 
  }
  
  console.log(qux); 
  qux(); 
}

foo();

UPDATE:

The error is a TypeError because the function declaration is hoisted to the top of the parent function scope. If the function is never declared, then you will get a ReferenceError message.

  • Related