Skip to content

Commit c76ea74

Browse files
committed
Fix object iteration by using Object.values() instead of for-of
1 parent b057112 commit c76ea74

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

‎Sprint-2/debug/author.js‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// This program attempts to log out all the property values in the object.
44
// But it isn't working. Explain why first and then fix the problem
55

6-
const author = {
6+
/* const author = {
77
firstName: "Zadie",
88
lastName: "Smith",
99
occupation: "writer",
@@ -14,3 +14,21 @@ const author = {
1414
for (const value of author) {
1515
console.log(value);
1616
}
17+
*/
18+
19+
// Prediction and Explanation
20+
/* The line "for (const value of author) {console.log(value);}" will not work because for-of is used only for iterable things, e.g: arrays, strings, maps, sets.
21+
But author is a plain object (created with {}), and plain objects are not iterable. So Javascript throws: TypeError: author is not iterable because objects don't have a natural order to loop through. */
22+
23+
// Corrected code
24+
const author = {
25+
firstName: "Zadie",
26+
lastName: "Smith",
27+
occupation: "writer",
28+
age: 40,
29+
alive: true,
30+
};
31+
32+
for (const value of Object.values(author)) {
33+
console.log(value);
34+
}

0 commit comments

Comments
 (0)