简体   繁体   中英

JS trivia - defining function inside if condition

Why does this code print undefined instead of function :

if (function f(){}) {
    console.log(typeof f);
}

...while this one prints function as expected:

eval('function g(){}');
console.log(typeof g);

(And also if (x = 42) console.log(x); prints 42 as expected.)

NOTE: I am perfectly aware that this kind of code is bad practice, and I know that most linters would also reject it, as they should... but I'm just curious what is the logic behind Javascript's interpreter's behavior.

Because the name of the function in a named function expression is not added to the scope where the expression occurs (unlike a function declaration , where the name is added to the scope where it occurs). With an NFE, the name is only in scope within the function. The one in your if is an NFE. The one in your eval is a declaration.

Examples:

 // NFE var x = function foo() { console.log("2: ", typeof foo); // function }; console.log("1: ", typeof foo); // undefined x(); // Declaration function bar() { } console.log("3: ", typeof bar); // function 

When the function production is being used as a value (eg, in the if , or on the right-hand side of an assignment, etc.), it's an expression. When it's standalone, it's a declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM