Why does the ternary operator with the some method make this statement false?

Viewed 47

Couple of questions here. This is from Wes Bos' 30 Days of JavaScript course.

  1. Why does the ternary operator (commented out) make this false?
  2. Why is my solution incorrect?

Challenge

const people = [
    { name: 'Wes', year: 1988 },
    { name: 'Kait', year: 1986 },
    { name: 'Irv', year: 1970 },
    { name: 'Lux', year: 2015 }
];

// Array.prototype.some() // is at least one person 19 or older?
// Array.prototype.every() // is everyone 19 or older?

Wes' Solution

const isOlderThan19 = people.some(function(person) {
    const currentYear = new Date().getFullYear();
    // (currentYear - person.year >= 19) ? true : false
    if (currentYear - person.year >= 19) {
        return true;
    }
});

My Solution

const isOlderThan19 = (element) => {
    let age = new Date().getFullYear() - element.year;
    age >= 19;
}

console.log(people.some(isOlderThan19));

I tried logging the ages that are being set to the console. All but one of the people are over 19 but it returns false. I'm trying to understand why.

3 Answers

1- The ternary operator has no return before it, so the function defaults to return undefined, which is not desired.

2- isOlderThan19 is not returning anything, you probably missed the return word before age >= 19

Both examples fails due to missing the return statement.

Try this

const isOlderThan19 = (element) => {
    let age = new Date().getFullYear() - element.year;
    return age >= 19;
}

console.log(people.some(isOlderThan19));

Your ternary statement needs to actually return, and not just be a boolean

(currentYear - person.year >= 19) ? return true : return false

or more accurately

const isOlderThan19 = people.some(function(person) {
    const currentYear = new Date().getFullYear();
    return (currentYear - person.year >= 19) ? true : false
});
Related