Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda