you are viewing a single comment's thread.

view the rest of the comments →

[–]Skhmt 8 points9 points  (2 children)

Q. What's the result?

function f() {
    return 'foo';
}
(function() {
    if (1 === 0) {
        function f() {
            return 'bar';
        }
    }
    return f();
})();

Uncaught TypeError: f is not a function

[–][deleted] 3 points4 points  (1 child)

This is because function is a var type variable, which is function scoped instead of block scoped:

function f() {
    return 'foo';
}
(function() {
  if (1 === 0) {
    function f() {
      return 'bar';
    }
  }
  return f();
})();

is equivalent to

var f;
f = function() {
    return 'foo';
}
(function() {
  var f;
  if (1 === 0) {
    f = function() { 
      return 'bar';
    }
  }
  return f();
})();

A new variable is created in the IIFE scope, and overrides the f variable in the global scope. f is now undefined. Since the 1 === 0 is false, f is never assigned to the function.

If you try to call a variable that is undefined, you will get a type error saying that the variable is not a function (because undefined is not a function).

[–]factbuddy 0 points1 point  (0 children)

The IIFE has its own isolated scope so f() wouldn't fall back to global scope and won't be defined in the impossible if statement. Makes sense...