2

I have actually no idea how the output of this code is a number. Someone kindly help understanding with what logic is JS running in this example?

<script>

var f = (
  function f(){ return "1"; }, 
  function g(){ return 2; }
)();

console.log(typeof f);

</script>
adiga
  • 34,372
  • 9
  • 61
  • 83
Deadpool
  • 7,811
  • 9
  • 44
  • 88

4 Answers4

4

You're using the comma operator. You're basically executing g here

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

var f = (
  function f(){ return "1"; }, 
  function g(){ return 2; }
)()

is similar to:

var temp = function g(){ return 2; }
f = temp() // returns 2
adiga
  • 34,372
  • 9
  • 61
  • 83
  • is there any logic somewhere or rule or documentation for this? Also, what if I am writing 10 functions inside () and executing them? what will happen then? what if the last one returns nothing? – Deadpool Feb 26 '19 at 09:21
2

Because of the comma operator.

x = a, b;

This evaluates a, then it evaluates b, and the result of b is used. That is, a is only evaluated for its side effects, otherwise its result is discarded.

That means that

var f = (
   function f(){ return "1"; }, 
   function g(){ return 2; }
)();

is a fancy way of writing

var f = (function g(){ return 2; })();

which is a fancy way of writing

var f = 2;

and 2 is a number.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

Here f is not a function.

Instead contains the value returned by g function.

f currently holds to the value returned in IIFE

var f = (
  function f(){ return "1"; }, 
  function g(){ return 2; }
)();

console.log(f);

</script>
Monica Acha
  • 1,076
  • 9
  • 16
1

So, right, the comma operator. But more important is the change of the context of the functions. They are not anymore accessable from the global scope.

Some expanations may be in this answer of Does the comma operator influence the execution context in Javascript?:

var f = (
        function f() { return "1"; }, 
        function g() { return 2; }
    )();

console.log(f);
console.log(typeof f);
console.log(g()); // throws error: 'g' is not defined
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392