LearnFrenzy
Sign in Take a free test

Arrow Functions · Predict the Output · Question 19

An arrow property using the variable name Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
const cart = {
  items: [100, 200],
  total: () => cart.items.reduce((a, b) => a + b, 0),
};
cart.items.push(50);
console.log(cart.total());
  • A 300
  • B 350 Correct
  • C undefined
  • D TypeError
Correct Answer: Option B

The arrow does not use this; it reads the cart variable when it runs, so it sees the pushed item. (It would break if the object were copied or renamed – methods with this are more robust.)

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