Skip to content

OutputNot attempted

Constructor that returns something

function A() {
this.x = 1;
return { x: 2 };
}
function B() {
this.x = 1;
return 5;
}
console.log(new A().x, new B().x);

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

If a constructor returns an OBJECT, new gives you that object instead of this. Returning a primitive is ignored.