0

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?

2
  • 2
    I'm not sure what you mean by 'self-invoking function' - you have a series of functions, the last one of which (h) is invoked. Commented Aug 6, 2012 at 11:49
  • 2
    This question is similar to: What does the comma operator do in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 28, 2024 at 21:50

3 Answers 3

6

Because the functions are separated by the , comma operator.

This evaluates the separated expressions, and returns the result of the last expression.

var x = ("a", "b", "c"); console.log(x); // "c" 

So in your case, the last function is returned, as the result of the enclosing () group, and that's the one invoked by the trailing () function call.

 // result from group---v v---invoked var f = (func1, func2, func3)() 
Sign up to request clarification or add additional context in comments.

Comments

2

Let's break this down.

The comma operator in Javascript evaluates several expressions, and returns the last one:

>>> "a", 1 1 >>> 1, "a" "a" 

So when you take three anonymous functions and string them together with commas, it evaluates to the last one:

>>> (function f(){ return "123"; }, function g(){ return 2; }, function h(){ return "test"; }) function h(){ return "test"; } 

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.

2 Comments

Comma is also used in variable declaration list where it has different semantics I.E var a, b, c;
1

The comma operator returns the last item. What you are doing is like:

var f = function(){}, function(){}, "string"; 

Which will make f a string, because only the last function is being called.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.