LearnFrenzy
Sign in Take a free test

Objects · Find the Error · Question 14

Bug: the total contains text Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
const base = { currency: "INR" };
const prices = Object.create(base);
prices.pen = 10;
prices.book = 50;
let total = 0;
for (const k in prices) total += prices[k];
console.log(total);
  • A Object.create copies base into prices
  • B prices.pen must be a string
  • C += cannot add numbers
  • D for…in also visits the inherited currency key, adding "INR" – loop over Object.values(prices) instead Correct
Correct Answer: Option D

for…in walks enumerable keys of the prototype chain too. Object.values / Object.entries list own properties only, giving 60.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links