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

173
Visualizações
Why no compiler error for this closure function?

I am reading Marijn Haverbeke's excellent book, "Eloquent JavaScript". https://eloquentjavascript.net/

I do not understand this example on closures where number is not defined, yet there is no error.

Is number a function or a parameter?

There is nothing to indicate that number is passed in as parameter the second time.

function multiplier(factor) {
  return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));
// → 10
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Understanding how closures work is hard enough but when the example you're looking at arbitrarily mixes a function declaration with an arrow function - as this one does - if you don't understand how arrow functions work it makes it more difficult to understand.

Here's a slightly easier example that doesn't use an arrow function to show what's going on.

// `multipler` takes a factor as an argument
function multiplier(factor) {

  // It returns a function that - when it's called -
  // accepts a number
  return function (number) {

    // And the return from that function
    // is the factor * number
    return number * factor;
  }
}

// So we call `multipler` with a factor and assign the
// function it returns to our `twice` variable
let twice = multiplier(2);

// We can then call the function assigned
// to `twice` with a number, and the resulting
// return from that function will be factor * number
console.log(twice(5));

In terms of the example using that arrow function:

// We pass in a factor to the `multipler`
function multiplier(factor) {
  
  // We return a function that accepts a number
  // and returns factor * number
  // (I've added parentheses around the number
  // parameter to clearly show it)
  return (number) => number * factor;
}

// So we call `multipler` with a factor and assign the
// function it returns to our `twice` variable
let twice = multiplier(2);

// We can then call the function assigned
// to `twice` with a number, and the resulting
// return from that function will be factor * number
console.log(twice(5));

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