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

178
Views
Why does forEach return undefined?

Here is my code to solve leetcode- Two sum

let nums = [2, 7, 11, 15];
let  target = 9;
for (let i = 0; i < nums.length; i++) {
  let x = target - nums[i];
  if (nums[i + 1] === x) {
    console.log([i, i+1]) // [0, 1]
    return [i, i + 1];
  }
}  //it ok
nums.forEach((item, index) => {
  let x = target - nums[index];
  if (nums[index + 1] === x) {
    console.log([index, index + 1]);// [0, 1]
    return [index,index+1]
  }
}); // undefined

I use forEach instead of for(...), both console.log are same, but forEach returns undefined. Why?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use JS map because the forEach always return undefined

let nums = [2, 7, 11, 15],
  target = 9;
let m = {};
nums.map((value, index) => {
  m[value] = index;
});

for (i = 0; i < nums.length; i++) {
  let diff = target - nums[i];
  if (m.hasOwnProperty(diff)) {
    console.log(i, m[diff]);
  }
}
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!