Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29109

Create an array with or without `new`

There are two ways to create an array using the array constructor

new Array(1,2,3)
Array(1,2,3)

I would say that the first (with the new keyword) is preferred or is it of no importance ?

UPDATE: In my case I use this type of array construction because I do:

new Array(someNum).join('x');

Upvotes: 2

Views: 133

Answers (1)

thefourtheye
thefourtheye

Reputation: 239453

If a function is meant to be used only as a constructor function, then one can use the common pattern,

function ConstructorFunction() {
    // If the current object is not an instance of `ConstructorFunction`
    if (!(this instanceof ConstructorFunction)) {
        return new ConstructorFunction();
    }
    ...
}

Something similar to that would be done in the Array constructor as well.

Note: It is always better to use new, if you intend to use a function as a constructor function.

Upvotes: 4

Related Questions