Home > database >  Why is my variable returning as 'undefined' despite being set a value?
Why is my variable returning as 'undefined' despite being set a value?

Time:01-23

Relatively new to javascript. Just cannot seem to find out why this code doesn't work.

This is part of the Odin Project's javascript exercises, exercises 12: https://github.com/TheOdinProject/javascript-exercises/tree/main/12_findTheOldest

Currently just working on the first part of the tests for this exercise. After returning the variable, it returns with "undefined" and fails the test.

Here is my code. I know it's most likely far from efficient but I'd like to know why this specific way, even if not ideal, doesn't work when tested in the terminal (unless this method just doesn't work at all in this specific circumstance and test). While returning the value returns "undefined", returning it through console.log displays that the variable does have the correct answer stored.

const findTheOldest = function(people) {
    withAges = people.map(x => ({
        ...x, age: Number(x.yearOfDeath) - Number(x.yearOfBirth)
      }));
    let max = Math.max(...withAges.map(x => { return x.age; }));
    let maxFind = withAges.find((x => { return Number(x.age) == Number(max); }));
    let maxName = maxFind.name;
    return maxName;
    //return console.log(maxName) returns the correct answer which is the name Ray.
};

module.exports = findTheOldest;

Here is the spec.js code that tests the result of my code and returns undefined.

const findTheOldest = require('./findTheOldest')

describe('findTheOldest', () => {
  test('finds the oldest person!', () => {
    const people = [
      {
        name: "Carly",
        yearOfBirth: 1942,
        yearOfDeath: 1970,
      },
      {
        name: "Ray",
        yearOfBirth: 1962,
        yearOfDeath: 2011,
      },
      {
        name: "Jane",
        yearOfBirth: 1912,
        yearOfDeath: 1941,
      },
    ]
    expect(findTheOldest(people).name).toBe('Ray');
  });
});

CodePudding user response:

You return the name instead of the object.

You are actually reading 'Ray'.name which is undefined.

Try remove the .name and you will have it.

  • Related