A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

confused about js function syntax

I was doing some ES6 syntax practice on freecodecamp.org, having some difficulties to understand the context.I know this is called IIFE in JS,

(function () {
    statements
})();

So, this is OK but why not I get the ..args inside the first sum also instead of the inner sum only?

const sum = (function(...args) {
  console.log(...args); //this shows nothing
  return function sum(...args) {
    console.log(...args); // this shows 1,2,3
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3)); // 6

What if I modify the above snippet with this, they are doing the same thing right? is there any logical difference happening under the hood?

function sum(...args) {
  console.log(args);
  return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

The main problem is why a function sum returning another function sum inside it.

Upvotes: 1

Views: 82

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

In the first code, the IIFE is being called with no arguments, see:

})();

So, the resulting args array is empty, when spread into a parameter list, the resulting parameter list is empty; there is nothing to log. console.log with an empty parameter list does not do anything. It would log something if you invoked the IIFE with at least one argument, though:

const sum = (function(...args) {
  // Now, it shows something!
  console.log(...args);
  return function sum(...args) {
    console.log(...args); // this shows 1,2,3
    return args.reduce((a, b) => a + b, 0);
  };
})(9999);
console.log(sum(1, 2, 3)); // 6

In the second code, there's only one function, not a function wrapped inside another function, and that one function is always called with parameters. If you called it with no parameters and spread them into the console.log, you would see the same effect:

function sum(...args) {
  console.log(...args);
  return args.reduce((a, b) => a + b, 0);
}
sum(); // 6

Upvotes: 4

Related Questions