LearnFrenzy
Sign in Take a free test

Arrow Functions · Predict the Output · Question 12

An arrow passed to setTimeout in a class Answer, explanation & discussion

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

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

main.js
class Greeter {
  constructor() { this.msg = "Hi"; }
  later() { setTimeout(() => console.log(this.msg), 0); }
}
new Greeter().later();
console.log("first");
  • A first Hi Correct
  • B Hi first
  • C first undefined
  • D TypeError
Correct Answer: Option A

The timer callback runs after the current script finishes, so "first" prints first. The arrow keeps later()'s this, the Greeter instance.

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