Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
  });
});

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading