1

I'm kinda new in JavaScript, I know that there are different ways how to traverse array of objects, but I found a tutorial and didn't get this ${person.name} part. Code is:

let personData = [
  { name: "Dylan", age: 31 },
  { name: "Hannah", age: 17 },
  { name: "Dollan", age: 39 },
  { name: "Elle", age: 3 },
];

function loadTableData(personData) {
  for (let person of personData) {
    dataHtml += `<tr><td>${person.name}</td><td>${person.age}</td></tr>`;
  }
}

I tried to understand what exactly is happening so I put `${personData.name}` to console and I get "undefined" = $3 My question is, why this works fine within for loop, but in console I'm getting undefined?

8
  • What don't you understand about person.name? person is the current object in the loop, and person.name is the value of the name property. So when person == {name: 'Dylan', age: 31 }, person.name == 'Dylan' Commented Nov 21, 2021 at 14:30
  • 5
    The person variable is local to the loop, it's created by for (let person of personData). So it's not defined if you just type person.name in the console. Commented Nov 21, 2021 at 14:31
  • 1
    In your loop you write person.name, not personData.name. Commented Nov 21, 2021 at 14:33
  • 1
    Inside of your for loop add console.log(person.name);... I think it'll clear your confusion up for you. Or in console you would need to select an index like this: personData[0].name to see it outside of the loop. Commented Nov 21, 2021 at 14:34
  • 1
    Try in your console: personData[0].name and see what happens. What the for...of does is take each item of array and select a item as the variable you choose. If you have chosen for (let potato of pensonData) it would work as well. Potato would have been the name of the each object that only exists within the for loop. Commented Nov 21, 2021 at 14:36

2 Answers 2

1

From your example, personData is the array of objects, to access each item you access it inside the loop with a local variable person. Console will log undefined for ${personData.name} instead you can access an item of the array through index, try this ${personData[0].name} which will print the vale of name property in your first item.

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

Comments

0

If you iterate over the personData object, you will get undefined with your given code. You can try the following:

personData.forEach(function (person ) {
     dataHtml += `<tr><td>${person.name}</td><td>${person.age}</td></tr>`;
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.