0

I recently had an interview question where I was shown this block of code (without the answer) and asked what would be printed to the console:

var i = 1;

if(function f(){}) {
  i += typeof f;
}

console.log(i);

// prints "1undefined"

I understand that typeof returns a string. Implicit type conversions combines the string from the typeof evaluation and the number into '1undefined'. However, I thought it would print '1function'.

What I don't completely understand, is why f is not in scope?

Is this not even a scope issue? Is the function declaration solely a Logical expression that gets evaluated to true as part of the if statement, and then no longer exist in any scope?

Any clarification would be greatly appreciated.

  • 1
    The function is declared in the parentheses and is not passed down. Inside of the parentheses, you can use it. – Rojo Jan 21 '21 at 14:51
  • The function name in that case is not supposed to be bound into the enclosing scope. In some old browsers, it was (erroneously), but I don't think that's been true for a lot of years. The function name is only bound *inside* the function, so outside there's no symbol `f`. – Pointy Jan 21 '21 at 14:52
  • @Rojo no, it's not bound externally (to the function itself) at all. – Pointy Jan 21 '21 at 14:52

2 Answers2

2

f is not in scope because it is an inline named function expression. It is not a function declration. The differences are subtle but important -

// declaration
function f () { ... }

// named function expression
const foo = function f () { ... }

// named arrow expression
const f = () => { ... }

// unnamed arrow expression
() => { ... }

The semantics of if help us understand -

if (<expression>) {
  <consequent>
} else {
  <alternative>
}

As you can see, the conditional supplied to an if statement must be an expression. You cannot declare a variable in an expression. This includes function declarations.

Thank you
  • 107,507
  • 28
  • 191
  • 224
1

The function statement is inside parentheses. This makes it a function expression and not a function declaration.

The variable f only exists inside the function.

(function f(){ /* i.e. here */ })

Outside the function there is no f, so you get undefined as you would for any other variable that doesn't exist in the current scope.

console.log(typeof f);
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205