Using the Rest Operator with Function Parameter example

Hello, strangers.
I’m new to programming so I’m quite confused and clueless most of the time. Can someone explain why there’s an opening parenthesis before the function keyword? Also, why create a function called sum and then return that exact function? I’ve never seen anything like this before. Thanks in advance.

const sum = (function(...args) {
  "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

Link to the challenge:


the parenthesis make it an Immediately Invoked Function Expression (IIFE). “A common pattern in JavaScript is to execute a function as soon as it is declared.” They are explained later in the curriculum ( JavaScript Algorithms And Data Structures Certification > Object Oriented Programming > exercises:
Understand the Immediately Invoked Function Expression (IIFE) and Use an IIFE to Create a Module) There is also a video by Beau: Immediately Invoked Function Expression - Beau teaches JavaScript

I am not sure about the return.


Good question : why create a function called sum and then return that exact function?
const sum define a constant reference to function sum(...args){...}.
if we try this :

function sum(...args) {
  return -1;

we get this error :

SyntaxError: redeclaration of const sum

this protect sum from being accidentally changed when code grow.

1 Like