Could you please explain me the purpose of the parenthesis(in bold) on the following code?
Thank you.
const sum =(function() {
“use strict”;
return function sum(x, y, z) {
const args = [ x, y, z ];
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); // 6
1 Like
This is what’s called an immediately-invoked function expression (or IIFE). Adding those parentheses right immediately after the function invokes it on the spot. It’s similar to this:
function _iife() {
'use strict';
// rest of the function...
}
// notice the parens? They're invoking _iife.
// The same way they invoke the function in the code you posted.
const sum = _iife();
console.log(sum(1,2,3)); // 6
except that an IIFE almost always doesn’t need a name, and that an IIFE is only used on one place.
1 Like
Thank you for your quick response kevcomedia, I am not sure if I clearly understand this. There is already “()” just after the word “function” and then there is the second “()” just before “)” I understand the outer “()” it is the grouping operator according to MDN link you sent. Is this IIFE the second “()”? Also, when I remove the parenthesis both outer(grouping operator) and IIFE the code doesn’t run but it looks like it should return a value(see below).
const sum = function() {
“use strict”;
return function sum(x, y, z) {
const args = [ x, y, z ];
return args.reduce((a, b) => a + b, 0);
};
};
console.log(sum(1, 2, 3)); // doesn’t return a value
The entire function plus the other pair of parens is the IIFE. Without that last pair of parens (regardless whether you keep the grouping parens or not), it’s just a plain function assigned to a variable.
1 Like
Thank you very much for the explanation kevcomedia.
1 Like