liveBook · Manning

Constructor return value

As explained in Secrets of the JavaScript Ninja, Second Edition

The value produced by a constructor call, where an explicitly returned object replaces the newly created instance and a nonobject return is ignored.

Calling a function with `new` normally returns the newly created object. An explicit primitive return, such as a number, is ignored; an explicit object replaces that new instance. section 4.2.3

Listing 4.8. Constructors returning primitive values
function Ninja() {                                             #A
  this.skulk = function () {
    return true;
  };
  
  return 1;                                                    #B
}
assert(Ninja() === 1,                                          #C
  "Return value honored when not called as a constructor");    #C

var ninja = new Ninja();                                       #D

assert(typeof ninja === "object",                              #E
  "Object returned when called as a constructor");             #E
assert(typeof ninja.skulk === "function",                      #E
  "ninja object has a skulk method");                          #E

The constructor returns `1`, but `new Ninja()` still produces an object with its `skulk` method. section 4.2.3

Listing 4.9. Constructors explicitly returning object values
var puppet = {                                       #A  
  rules: false                                       #A
};                                                   #A
            
function Emperor() {                                 #B
  this.rules = true;                                 #B
  return puppet;                                     #B
}

var emperor = new Emperor();                         #c

assert(emperor === puppet,                           #D
  "The emperor is merely a puppet!");                #D
assert(emperor.rules === false,                      #D
  "The puppet does not know how to rule!");          #D

`Emperor` initializes the new instance, then returns `puppet`; the constructor call’s result is that existing object. section 4.2.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Compares primitive and object returns with worked examples, without exploring deeper runtime internals.
Examples
Contrasts `Ninja` returning a number with `Emperor` returning the `puppet` object.
What it assumes
Assumes familiarity with constructor functions, `new`, and `this`.
What you can do after
Evaluate whether a constructor call returns its new instance or an explicitly returned object.
How it connects
Connects constructor functions and the `new` operator to function invocation and `this`.

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.