JavaScript · Middle · Question 1 of 75

What does this code print?

const user = {
  name: "Ann",
  greet() { return this.name; },
};
const greet = user.greet;
console.log(greet());

Explanation

this is determined by how a function is called, not where it's declared. greet() is called without an object before the dot, so this is undefined in strict mode (the global object in sloppy mode). Fix it with user.greet.bind(user) or by calling user.greet().

Further reading

Problem with a question

JavaScript · Middle · question 1

Test yourself

Take the JavaScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz