Search code examples
javascriptnode.jstypeof

why i get the return "undefined" by typeof and how i can prevent this?


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?


Solution

  • 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 --------------------^