skip to Main Content

Sorry for the poorly phrased question. I came across this code when trying to understand how to maintain state across different function calls in javascript, and I don’t understand its behaviour. It seems like it is returning a function, not a number. Why is typeof(f()) == 'number' true then?

var f = function() {
  var state = 1;
  return function() {
    return state++;
  };
}();

console.log(typeof f());

3

Answers


  1. your code is returning the inner function as you added () at the end of your code and you are calling that returned function and checking the type of that returned value which is a number.

    console.log(typeof f) // function
    console.log(typeof f()) // number
    
    Login or Signup to reply.
  2. Its behaviour is simple. f is a function, but when you say f() it will actually calls the function and the function returns a number.

    typeof(f) —> function

    typeof(f()) —> typeof(return value of f function) – which is a number

    Thats why typeof(f()) === number

    Login or Signup to reply.
  3. Because you called the function when you initialized f and, when you call f, basically you call the function that was returned by the outer function. Let’s see without the paranthesis at the end of the initialization:

    var f = function() {
      var state = 1;
      return function() {
        return state++;
      };
    };
    
    console.log(typeof f());

    As you can see, it’s a function then. Now, let’s add the () your code has and now it’s a number:

    var f = function() {
      var state = 1;
      return function() {
        return state++;
      };
    }();
    
    console.log(typeof f());

    So, basically you define a function and evaluate it, assigning the function it returns to f, so the type of f‘s result is a number.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search