JavaScript - Problem With Eval And Named Function Expression
// JavaScript - Problem with eval and named function expression:
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y);
The above code will log '1undefined' instead of '1function' because the condition
of the if statement is evaluated inside an eval statement so it does not create
the function with the name f, even though it evaluated to true, and therefore
'typeof f' is 'undefined'. The above code is equivalent to:
var k = 1;
if (1) {
eval(function foo(){});
k += typeof foo;
}
console.log(k);
However, consider:
var k = 1;
if (1) {
function foo(){};
k += typeof foo;
}
console.log(k);
The above code will log '1function';
page revision: 0, last edited: 14 Nov 2016 07:08