LearnFrenzy
Sign in Take a free test

Objects · Predict the Output · Question 5

A method called on its own Answer, explanation & discussion

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

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

main.js
const user = {
  name: "Asha",
  hi() { return "Hi " + this.name; },
};
const hi = user.hi;
console.log(user.hi(), "|", hi());
  • A Hi Asha | Hi Asha
  • B Hi Asha | TypeError
  • C Hi undefined | Hi undefined
  • D Hi Asha | Hi undefined Correct
Correct Answer: Option D

this depends on how the function is called. hi() has no object before the dot, so (non-strict) this is the global object, which has no name property. In strict mode it would throw.

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