Hovhannes Gevorgyan
Hovhannes Gevorgyan

Reputation: 552

Get an error when I call object's properties in Array

In typescript code I have an array with objects in it. When I call "getUsers(users)" function, it returns the result as I need, but in console I get this error "Uncaught TypeError: Cannot read property 'firstName' of undefined at getUsers (index.js:20) at index.js:23"

let users = [
{
    firstName: "John",
    lastName: "Doe",
    age: 34
},
{
    firstName: "Jack",
    lastName: "Jackson",
    age: 23
},
{
    firstName: "Ann",
    lastName: "Watson",
    age: 24
}
];
function getUsers(users) {
for (var i = 0; i <= users.length; i++) {
    console.log(users[i].firstName + " is " + users[i].age + " years old!");
}
}
getUsers(users);

Upvotes: 0

Views: 58

Answers (4)

Hung Quach
Hung Quach

Reputation: 2177

You can use for-of loop

let users = [
{
    firstName: "John",
    lastName: "Doe",
    age: 34
},
{
    firstName: "Jack",
    lastName: "Jackson",
    age: 23
},
{
    firstName: "Ann",
    lastName: "Watson",
    age: 24
}
];
function getUsers(users) {
    for (var user of users) {
         console.log(user.firstName + " is " + user.age + " years old!");
    }
}

getUsers(users);

Upvotes: 0

lumio
lumio

Reputation: 7575

Your for loop exceeds the available array items. The heighest ID is users.length - 1.

So the easiest way is to remove the equal-sign.

Also think of using the buildt in forEach or map function like this:

function getUsers( users ) {
  users.forEach( u => {
    console.log( `${ u.firstName } is ${ u.age } years old!` );
  } );
}

Upvotes: 2

atiq1589
atiq1589

Reputation: 2327

it should be less than length not less than equal to

for (var i = 0; i < users.length; i++) {
   console.log(users[i].firstName + " is " + users[i].age + " years old!");
}

Upvotes: 1

brk
brk

Reputation: 50291

The issue is with i <= users.length , it need to be i < users.length.i++ will increment the value of i by 1 but the length is three and the index start from 0 so the elements are occupied till second index, hence i <= users.length will actually try to access the element in the third index which is unefined

let users = [{
    firstName: "John",
    lastName: "Doe",
    age: 34
  },
  {
    firstName: "Jack",
    lastName: "Jackson",
    age: 23
  },
  {
    firstName: "Ann",
    lastName: "Watson",
    age: 24
  }
];

function getUsers(users) {
  for (var i = 0; i < users.length; i++) {
    console.log(users[i].firstName + " is " + users[i].age + " years old!");
  }
}
getUsers(users);

Upvotes: 2

Related Questions