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 functionsum
inside it.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.