jeudi 21 janvier 2021

In JavaScript, what is the scope of a function declared within the condition of an if statement? [duplicate]

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.

Aucun commentaire:

Enregistrer un commentaire