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

189
Views
javascript map function returned undefined
const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
  if (index < 3) {
    return num;
  }
});

// filteredNumbers is [1, 2, 3, undefined]

According to my understanding callback function should return all numbers of array if their index is less than 3 so it should return 1,2,3 and stop after that and number 4 can not be returned as if condition says index should be less than 3. I am wondering why it returned undefined for index 3 number.

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

0

.map is an isomorphism and preserves the length of the given array.

So if the callback function does not return anything, the index will be undefined.

about 4 years ago · Juan Pablo Isaza Report

0

You want to user a filter function instead if you need to filter array elements that meet a certain condition.

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.filter((_, index) => index < 3);

console.log(filteredNumbers);

about 4 years ago · Juan Pablo Isaza Report

0

If you want just to get the first 3 items in the array, I recommend using slice.

const numbers = [1, 2, 3, 4];
console.log(numbers.slice(0, 3));

Second solution is use filter instead of map.

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.filter((num, index) => {
  return index < 3
});

console.log(filteredNumbers)

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!