Getting the largest number of an object property in an array using .reduce()

I was reading a medium article and came across this code. It returns the object with the most experienced pilot using .reduce() . I can’t wrap my head around the expression (oldest.years || 0) . Why not just use (oldest.years ) ?

var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
];

var mostExpPilot = pilots.reduce(function (oldest, pilot) {
  return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});

console.log(mostExpPilot);```

Off the top of my head, it would cover if that property were undefined, using 0 instead. I’m not sure that it’s actually needed. I also am not sure why they bother to give a starting value - if they left that undefined, reduce would just use the first element and then start looping on the second.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.