JavaScript - Problem With Eval And Named Function Expression

javascript

// 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';
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License