Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is the best practice to follow when declaring an array in Javascript? [duplicate]

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();?

like image 737
user1517223 Avatar asked Jul 30 '12 06:07

user1517223


2 Answers

[] 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!

like image 169
Quentin Avatar answered Sep 28 '22 23:09

Quentin


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().

like image 40
Nirav Limbasiya Avatar answered Sep 28 '22 23:09

Nirav Limbasiya