skip to Main Content

following code:

"use strict"

 const students = [
  {firstname: "Max", lastname: "Mustermann", age: 21},
  {firstname: "Laura", lastname: "Müller", age: 25},
  {firstname: "Julia", lastname: "Schreiber", age: 30},
  {firstname: "Tobias", lastname: "Lieb", age: 19}
]

console.log( typeof students.age)


returns undefined. I don’t understand why. I also added in my code a student with an empty property age and tried to get the average like the following:

students.push({
  firstname: "Christian",
  lastname:"Schmidt",
  age:null
})

let ageSum = 0

for (const student in students){
 if(typeof student.age){
  ageSum += student.age
 }
}

here again, i don’t understand why the typeof returns undefined. Is there a better way in JavaScript to check the type object properties before processing them?

2

Answers


  1. students doesn’t have an age property, hence it’s undefined. If you want to refer to an individual student’s age (using the subscript operator), you’ll see it is indeed a number:

    "use strict"
    
     const students = [
      {firstname: "Max", lastname: "Mustermann", age: 21},
      {firstname: "Laura", lastname: "Müller", age: 25},
      {firstname: "Julia", lastname: "Schreiber", age: 30},
      {firstname: "Tobias", lastname: "Lieb", age: 19}
    ]
    
    console.log( typeof students[0].age)
    // Here --------------------^
    Login or Signup to reply.
  2. Messed with your code a bit. I prefer using an indexer when iterating javascript arrays like you were.

    const students = [
          {firstname: "Max", lastname: "Mustermann", age: 21},
          {firstname: "Laura", lastname: "Müller", age: 25},
          {firstname: "Julia", lastname: "Schreiber", age: 30},
          {firstname: "Tobias", lastname: "Lieb", age: 19}
        ]
    
        console.log(`Age of first student is ${students[0].age} and it's of type ${typeof students[0].age}`)
    
        students.push({
            firstname: "Christian",
            lastname:"Schmidt",
            age:null
        })
    
        let ageSum = 0
    
        for (var i = 0; i < students.length; i++){            
            if(typeof students[i].age === "number"){
                console.log(`${students[i].firstname} is ${students[i].age}`)
                ageSum += students[i].age
            } else 
            {
                console.log(`${students[i].firstname} has no age entered or it's invalid`)
            }
        }
    
        console.log(`Total age of students is ${ageSum}`)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search