Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Javascript iife functions

I was following a beginners course of JavaScript and I've come across this code. But I don't understand why sum needs to be an IIFE function. Could you please help me understand how this code works exactly?

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In this case the variable args takes the arguments

const sum = function() { 
  return function sum(x,y,z) {
     const args = [1,2,3];
     return args.reduce((a,b) => a+b, 0);}; 
}();
 console.log(sum(1,2,3))

The reduce() method executes a reducer function for each value of an array. In this case you are taking first two elements of arrays, finding the sum of these two and the reduce method goes one by one to other elements.

Other example to explain you better

const numbers = [175, 50, 25];

function myFunc(total, num) {
   return total - num;
} // returns 100 (175 - 50 - 25)
about 4 years ago · Juan Pablo Isaza Relatório

0

In that function looks like is just to show you how to work the IIFE(the parentheses at the end of the function) that parenthesis is to auto-execute the function, the use is if you want to execute a function when this load you can add the "()" at the end or "+" at the beginning of the clause "function" like this "+function" to see more in details check the following link:

Immediately-Invoked Function Expression (IIFE)

about 4 years ago · Juan Pablo Isaza Relatório

0

There is no current reason the function is inside another executed function.

These are equivalent except that one gets returned immediately by a function. If I had to guess, the next instruction may talk about scoping or currying?, who knows.

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

const sum = function(x, y, z) {
    const args = [x, y, z];
    return args.reduce((a, b) => a + b, 0);
  };
console.log(sum(1, 2, 3))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda