0

So I have these two for loops. In the first loop the message says exactly what I want it to say; Hello Herbert, Hello Peter.

But in the second one it says; Hello undefined.

What is the difference between these two blocks of code, and why does the second one returns undefined?

let people = [
    {
        name: "Herbert",
        occupation: "Vildstaed",
        language: ["Finnish", "English", "German"]
    },
    {
        name: "Peter",
        occupation: "Skalnstead",
        language: ["German", "Livonian Dialect"]
    }
];

for(var i = 0; i < people.length; i++){
    alert("Hello " + people[i].name)
}

for(let person in people) {
    alert("Hello " + person.name)
}

3 Answers 3

2

let people = [
    {
        name: "Herbert",
        occupation: "Vildstaed",
        language: ["Finnish", "English", "German"]
    },
    {
        name: "Peter",
        occupation: "Skalnstead",
        language: ["German", "Livonian Dialect"]
    }
];

for(var i = 0; i < people.length; i++){
    alert("Hello " + people[i].name)
}

for(let person in people) {
    console.log(person);
    alert("Hello " + people[person].name)
}

As you can see the values person is getting is the index of the array, hence you need to access it using people[person]

Sign up to request clarification or add additional context in comments.

Comments

1

For in loop will return to you the keys, not the objects. So for the second case you the person is not the one which you expect. You can see it by showing only the person.

let people = [
    {
        name: "Herbert",
        occupation: "Vildstaed",
        language: ["Finnish", "English", "German"]
    },
    {
        name: "Peter",
        occupation: "Skalnstead",
        language: ["German", "Livonian Dialect"]
    }
];

for(let person in people) {
    alert("Hello " + person)
}

To do what you want you can use for of loop instead in ES6 version or just get by key

let people = [
    {
        name: "Herbert",
        occupation: "Vildstaed",
        language: ["Finnish", "English", "German"]
    },
    {
        name: "Peter",
        occupation: "Skalnstead",
        language: ["German", "Livonian Dialect"]
    }
];

for(let person of people) {
    alert("Hello " + person.name)
}

for(let person in people) {
    alert("Hello " + people[person].name)
}

Comments

0
for(let person of people) {
   alert("Hello " + person.name)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.