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
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.
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
Because you called the function when you initialized
f
and, when you callf
, basically you call thefunction
that was returned by the outerfunction
. Let’s see without the paranthesis at the end of the initialization:As you can see, it’s a function then. Now, let’s add the
()
your code has and now it’s a number:So, basically you define a function and evaluate it, assigning the function it returns to
f
, so the type off
‘s result is a number.