if condition evaluation in javascript using eval at runtime

Viewed 1552
 var y = 1;

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

The Output of this code is 1undefined. I get the reason that the condition in if statement is evaluated using eval at runtime, but I cannot understand why it is not outputting 1function.

2 Answers

You need to define the function outside the if braces, if not, the scope of f is restricted to the inside of the condition. If you reformulate like this it works:

var y = 1;
//Pick One:
var f = () => {}; //If you are using ES6

function f() {}; //If you are not using ES6

if (f) {
  y += typeof f;
}

console.log(y); // 1function

In your example, the function is only scoped within the brackets of the test condition of the if statement.

Try the following:

  var y = 1;
  var f = function() { };
  if (f) {
    y += typeof f;
  }
  console.log(y)

You can define the function in the if test if the pointer to function is defined outside.

      var y = 1;
      var f = null;
      if (f = function() { }) {
        y += typeof f;
      }
      console.log(y)

Related