5

Possible Duplicate:
Create an empty object in JavaScript with {} or new Object()?

When I want to declare a new array I use this notation

var arr = new Array();

But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []."

I didn't find a reason to avoid using the constructor. Is in some way less efficient than using []? Or is it bad practice?

Is there a good reason to use var arr = []; instead of var arr = new Array();?

Community
  • 1
  • 1
user1517223
  • 140
  • 5

5 Answers5

7

[] is:

  • shorter
  • clearer
  • not subject to new Array(3) and new Array(3,3) doing completely different things
  • cannot be overridden.

Example code:

var a = new Array(3);
var b = new Array(3,3);
Array = function () { return { length: "!" }; };
var c = new Array();
var d = [];
alert(a.length); // 3
alert(b.length); // 2
alert(c.length); // !
alert(d.length);​ // (still) 0​​​​​​​​

This code live - will try to create 4 alerts!

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • Good answer. BTW, I am intereted to know why you think new Array(3) and new Array(3,3) are conflicting? They perform completely different initializations. – Ashwin Prabhu Jul 30 '12 at 06:23
  • `[]` is also [faster](http://jsperf.com/literal-vs-constructor-array/4) on many browsers. – Frédéric Hamidi Jul 30 '12 at 06:23
  • @AshwinPrabhu — That they do completely different initialisations is my point. It requires maintainers to know that adding a second argument changes the meaning of the first argument. – Quentin Jul 30 '12 at 06:26
5

Mostly, people use var a = [] because Douglas Crockford says so.

His reasons include the non-intuitive and inconsistent behaviour of new Array():

var a = new Array(5);     // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it

Note that there's no way with new Array() to create an array with just one pre-specified number element in it!

Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ].

Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().

Nirav Limbasiya
  • 348
  • 1
  • 9
0

The recommended practice is to use

var arr = [];

Already answered here

Community
  • 1
  • 1
ThirdOne
  • 1,227
  • 9
  • 11
0

In javascript, you should use literal when you can.

var a = []; instead of var o = new Array();

var o = {}; instead of var o = new Object();

Similarly, don't do new String("abc");, new Number(1);, and so on.

xdazz
  • 149,740
  • 33
  • 229
  • 258
0

JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays.

//Bad way to declare objects and arrays
var person = new Object(), 
    keys = new Array();

The new keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead.

Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation.

//Preferred way to declare objects and arrays
var person = {}, 
    keys = [];

Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax.

//Preferred way to declare complex objects and arrays
var person = {
        firstName: "Elijah",
        lastName: "Manor",
        sayFullName: function() {
            console.log( this.firstName + " " + 
                this.lastName );
        }
    }, 
    keys = ["123", "676", "242", "4e3"];

Best Practice

You should declare all of your variables using their literal notation instead of using the new operation. In a similar fashion you shouldn’t use the new keyword for Boolean, Number, String, or Function. All they do is add additional bloat and slow things down.

The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out Douglas Crockford's post entitled JavaScript, We Hardly new Ya.

Bruno Schäpper
  • 1,220
  • 1
  • 13
  • 20