Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!