I tried looping names of front-end developers nested inside of objects(refer to code) and when I printed it to console it says display is not defined.
var employees =
{
sales: {
manager: {
name: 'Evan',
gender: 'Male',
age: 41,
salary: 2000
},
sales_rep: {
name: 'Cilian',
gender: 'Male',
age: 24,
slary: 1000
},
sales_executive: {
name: 'Joanna',
gender: 'Female',
age: 23,
salary: 1000
}
},
engineering: {
manager: {
name: 'Mike',
gender: 'Male',
age: 39,
salary: 3000
},
designer: {
userExperience: {
name: 'Amy',
gender: 'Female',
age: 25,
salary: 1000
},
userInterface: {
name: 'Jenna',
gender: 'Female',
age: 24,
salary: 1000
}
},
developer: {
frontEndDeveloper: {
name: 'John',
gender: 'Male',
age: 27,
salary: 2000
},
backEndDeveloper: {
name: 'Felix',
gender: 'Male',
age: 28,
salary: 2000
}
}
}
}
;
var display;
for (let sector in employees) {
display = `${sector}: ${employees.engineering.developer[sector].name}`;
}
First, I thought display scope was within the for loop so I moved display variable outside of the for loop. It’s been like 4 days since I started learning JavaScript so I am very new to the concepts.
3
Answers
If you just want to get the name of developer from the object and if frontEndDeveloper key will only contain single obect then you can directly get the frontEndDeveloper name from the object. Please check below updated code.
Let me know if it works for you or not.
Here you are trying to loop over each sector in the employees object, but trying to access employees.engineering.developer[sector].name. This can throw error because, since you are using for in loop, in first iteration , value of ‘sector’ will be ‘sales’, then ‘engineering’ and so on.
So, essentially you are trying to access employees.engineering.developer[‘sales’] in first iteration, which is undefined. That’s the error.
I assume you are trying to print the details under the ‘developer’ sector. Yopu can achieve this with the following code.
To understand for..in loop better, please refer MDN webdocs. They provide good examples.
First of all,
there is a concept about your "undefined" at "display" variable.
HOISTING (https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)
Otherwise, "console.log" executes faster than your loop so you get this "not declare".
In the other hand that’s a bad example but I hope
this could help to you as beginner.
Think about few things: