Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

What happens when a constructor returns an object?

Do you know what will be the output of this code?

JavaScript
function Person(name) {
  this.name = name;
  return { name: "Other" };
}

console.log(new Person("Ana").name);
Show answer and explanation

The answer is "Other".

new creates this and returns it, unless the constructor explicitly returns an object. Then that object replaces this. Returning a primitive like 5 would be ignored.

Take the full quiz Next question →

More this questions

  1. Why does this become undefined when you extract a method?
  2. Why does an arrow function method return undefined for this?
  3. Can you change this on a bound function with call()?
  4. Why does an arrow function in setTimeout keep this?
  5. What is the difference between call and apply in JavaScript?

Related topics