2

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');
2
  • 2
    Neither, use a literal: [1,2,3]. ;-) Commented Aug 18, 2015 at 13:56
  • True, I've updated my post to show an example of why I'm using this, thnx! Commented Aug 18, 2015 at 14:39

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"Something similar to that would be done in the Array constructor as well". Not according to ECMA-262: "When Array is called as a function rather than as a constructor, it also creates and initializes a new Array object", so it doesn't test its this, it always creates a new instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.