I have a self invoking function like this:
var f = (function f(){ return "123"; },
function g(){ return 2; },
function h(){ return "test"; })();
typeof f;
typeof f
is always the type of what is returned in the last function definition. Like if h
is last, then it is "string"
, but if I remove h
and have g
as last, then "number"
.
Could someone explain why?
Let's break this down.
The comma operator in Javascript evaluates several expressions, and returns the last one:
So when you take three anonymous functions and string them together with commas, it evaluates to the last one:
Evaluating that result executes the function, returning
"test"
.Whichever function is last in the comma-separated list will be executed, and decide the overall return value.