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?
person.name?personis the current object in the loop, andperson.nameis the value of thenameproperty. So whenperson == {name: 'Dylan', age: 31 },person.name == 'Dylan'personvariable is local to the loop, it's created byfor (let person of personData). So it's not defined if you just typeperson.namein the console.person.name, notpersonData.name.forloop addconsole.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].nameto see it outside of the loop.