mardi 30 avril 2019

how to fix 'Cannot read property of undefined'?

I'm trying to determine which object in an array has the longest name and logging that object to the console.

I can't seem to access the length of the name property in my if statement.

  let longest;
  for (let i = 0; i < instructors.length; i++) {
    if (instructors[i].name.length > longest.length) {
      longest = instructors[i];
    }
  }
  return longest;
};

console.log(instructorWithLongestName([
  {name: "Samuel", course: "iOS"},
  {name: "Jeremiah", course: "Web"},
  {name: "Ophilia", course: "Web"},
  {name: "Donald", course: "Web"}
]));
console.log(instructorWithLongestName([
  {name: "Matthew", course: "Web"},
  {name: "David", course: "iOS"},
  {name: "Domascus", course: "Web"}
]));

I expect the output of
{name: "Jeremiah", course: "Web"}
{name: "Domascus", course: "Web"}

but I get an error stating it cannot read property '.length'

Aucun commentaire:

Enregistrer un commentaire