Reputation:
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);
Upvotes: 0
Views: 46
Reputation: 9425
When we look at the documentation of Array.reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#parameters we can see that this is because the example code has an initialValue
of {}
which has no years
property.
Same would be:
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
return oldest.years > pilot.years ? oldest : pilot;
}, { years: 0});
Upvotes: 3