skip to Main Content

I am doing an online course and practising what I am learning.
I just wanted to create a function, that takes an object and loops through an array element of the object using forEach.

So I don’t want to change anything. The reason why I am doing it just to practice forEach method combined with an object.

When I use this following function, it displays this:

15
18
14
17
undefined

Normally it shouldn’t display undefined at the end. I wonder, what I did wrong with the coding.
Can you help me please?

    let student = {
    firstName: "Sam", //string
    lastName: "Doe", // string
    hasGraduated: false, // boolean
    age: 21, // number
    grades: [15, 18, 14, 17], // array of numbers
    interests: ["computers", "books"] // array of strings
};

function showContent(obj){
  obj.grades.forEach(function(grade){
    console.log(grade);
  })
}
console.log(showContent(student));

2

Answers


  1. Drop the last line console.log(showContent(student));

    because the function showContent does not have any return value, so the last line console will be undefined.

    Login or Signup to reply.
  2. You can just drop the last line console.log(showContent(student));
    Or instead of logging the grades in the fn you can return them.

    obj.grades.forEach(function(grade){
        return grade;
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search