LearnFrenzy
Sign in Take a free test

Arrow Functions · Predict the Output · Question 13

Detaching a class-field arrow and a method Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

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

main.js
class Btn {
  label = "Save";
  arrowClick = () => this.label;
  methodClick() { return this?.label; }
}
const b = new Btn();
const { arrowClick, methodClick } = b;
console.log(arrowClick(), methodClick());
  • A Save Save
  • B Save undefined Correct
  • C undefined undefined
  • D TypeError
Correct Answer: Option B

The field arrow captured the instance when it was created. The method, called on its own, has this = undefined (class code is always strict), so this?.label is undefined.

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