0

Premise:

So whether you construct from a function or es6 class or base class you are supposed to initialize like (for now let's ignore short-hand constructors):

const Fruit = function(name) {this.name = name}
class Ball {
  constructor(color) {this.color = color}
}

const apple = new Fruit('apple')
const red_ball = new Ball('red')
const ob = new Object()
const arr = new Array()

Confusion:

But here's the thing, if I killed the new keyword above in all statements:

  • Class

    Uncaught TypeError: Class constructor A cannot be invoked without 'new'

  • Function (Es5 class)

    Undefined

  • Array / Base Classes - It initialized correctly! but Why?

    [] or {}

Thoughts:

It could be a really stupid question, but I cannot find any references as to why that's the case, but this behavior seems to unanimously apply in Chrome, Firefox, Edge, and Node.js

AP.
  • 6,216
  • 2
  • 22
  • 31
  • 1
    To be a bit more explicit than the dupe, in the case of `Array()` vs `new Array()`, it's [because the spec says so](https://www.ecma-international.org/ecma-262/6.0/#sec-array-objects): _" When Array is called as a function rather than as a constructor, it also creates and initializes a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments."_ `Object` is along the same lines - the spec defines what happens. – James Thorpe Jan 23 '18 at 17:29
  • 1
    `Fruit` is a function, but does not return anything, hence `undefined` similarly, `Array` and `Object` are also functions, but they return array/object respectively. You'r `Ball` Class however, is a special kind of function that cannot be instantiated without the `new` keywork – Ahmed Musallam Jan 23 '18 at 17:29
  • @JamesThorpe Just what I was looking for! Thanks! – AP. Jan 23 '18 at 17:41

0 Answers0