Home > Software design >  Why does this function returns the last argument when called right after definition
Why does this function returns the last argument when called right after definition

Time:10-31

function foo(x) {
  return x;
}
foo(1); // returns 1 as expected

function bar(x) {
  return x;
}(1,2,3); // returns 3

I couldn't understand why does bar function returns the last argument. Can anyone explain it to me?

CodePudding user response:

Your bar() function is being interpreted as a function declaration and not as a function expression, as a result, the (1, 2, 3) is not the call syntax for functions (), but rather the grouping operator using the comma-operator, which returns the last value of 3 (which is then logged in the console). If it's on separate lines it may become clearer:

function bar(x) { // declares a function bar
  console.log("running"); // never logged
  return x;
}
// Uses the grouping operator `( )`, with the comma operator
(1,2,3); // returns 3

If you make bar() a function expression, then it will behave as expected (here I'm using the unary plus to achieve that):

 function bar(x) {
  console.log("running"); // logged
  return x;
}(1,2,3); // returns 1
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related