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

231
Visualizações
Why can't I use an anonymous function expression for accessing an array index position?

In JavaScript one can access array values using this syntax...

const arr = ["one", "two", "three"];
console.log(arr[0]); // "one"

...or using a defined function that returns a number to achieve the same result:

const arr = ["one", "two", "three"];
const fn = () => 0;
console.log(arr[fn()]); // "one"

I might be brain-afk, but I simply do not understand why the exact same thing does not work when using an anonymous function expression? Don't I clearly end up with 0 as an array index position assessor?

const arr = ["one", "two", "three"];
console.log(arr[() => 0]); // undefined
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

() => 0 returns a function, not the value returned when called.

You need to invoke the function instead:

const arr = ["one", "two", "three"];
console.log(arr[(() => 0)()]);

about 4 years ago · Juan Pablo Isaza Relatório

0

The main difference is about the concept of an anonymus function.

const arr = ["one", "two", "three"];
const fn = () => 0;
console.log(arr[fn()]);

Here you are assigning an anonymus function to the fn constant and you are invoking this function returning a 0 in the index.

In your last example you're just assigning the function without invoking the function so that's why it returns the undefined.

If you want to auto invoke an anonymous function you just need to call it like this:

(() =>0)() // check the last pair of parentheses
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