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

203
Views
TypeError: Cannot read properties of undefined (reading 'endsWith')

I am trying to print out all countries which end with 'land' from the countries array below:

const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]

newArr = [];

for (let i = 0; i <= countries.length; i++){
  console.log(countries[i])
  if (countries[i].endsWith('land') === true){
    newArr.push(countries[i])
  }
  else{
    continue
  }
}

However, I am having a TypeError: Cannot read properties of undefined (reading 'endsWith)

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

0

out of index try this

for (let i = 0; i <= countries.length - 1; i++) {
    console.log(countries[i]);
    if (countries[i].endsWith("land") === true) {
        newArr.push(countries[i]);
    } else {
        continue;
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

Don't use = because index will be one less than the array length!

const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]

newArr = [];

for (let i = 0; i < countries.length; i++){
  console.log(countries[i])
  if (countries[i].endsWith('land') === true){
    newArr.push(countries[i])
  }
  else{
    continue
  }
}

about 4 years ago · Juan Pablo Isaza Report

0

Hope you have already got the answer from comments and other answers, but here is few improvement you can do using array reduce and &&

const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]

const z = countries.reduce((acc, curr) => {
  curr.endsWith('land') && acc.push(curr);
  return acc;
}, []);
console.log(z)

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!