JS Daily 32 - Constructor Function Returning an Object

Published on 22 Dec, 2020

What is the output of following code?

function Person(name, age) {
  this.name = name;
  this.age = age;
  return {
    name: "Backbencher",
    age: 30
  }
}

const obj = new Person("Joby", 35);
console.log(obj);
----o----

The output is:

[object Object] {
  age: 30,
  name: "Backbencher"
}

Person is a constructor function. If a constructor function returns an object, every instance is assigned with that object.

On the other hand, if the constructor function returns a primitive value like number, string or boolean, then obj would have assigned with the newly created object. Here is a constructor function that returns a string value.

function Person(name, age) {
  this.name = name;
  this.age = age;
  return "Hello";
}

const obj = new Person("Joby", 35);
console.log(obj);

In that case, the output is:

[object Object] {
  age: 35,
  name: "Joby"
}