JS Daily 20 - Return From Constructor Function

Last updated on 10 Dec, 2020

What is the output of following code?

function Car(name) { = name;
  return "BMW";

const carObj = new Car("Mercedes");

The output is "Mercedes".

Here the constructor function Car() is explicitly returning a string value. But that is ignored when used with new keyword. The newly created instance object is assigned to carObj. Therefore outputs "Mercedes".

If the returned value is an object instead of "BMW", then that object is assigned to carObj. The newly created object is ignored.

--- ○ ---
Joby Joseph
Web Architect