0

Possible Duplicate:
What are the best practices to follow when declaring an array in Javascript?

Would be correct don't use new Array after of defining a variable using []?

var v = [];
v = Array(5); // is new necessary?
Community
  • 1
  • 1
  • 3
    The second line doesn't update the array created by the first line, it makes a new array that is unrelated to the the array created by the first line. (That would also be true if you used `[]` on both lines or `Array()` (with or without `new`) on both lines.) But from the phrasing of your question you seem to think it matters whether the variable originally referenced an array defined with an array literal `[]` - what are you getting at? – nnnnnn Oct 24 '12 at 10:46

7 Answers7

0

The first line creates an empty array.

The second creates an array with 5 elements, all of which have the value undefined.

There is no sense in using both of them. Which one to use depends on what you are trying to do, but the second form is not encountered very often in practice. It's very likely that the first is all you are going to need.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

You are reassigning the value of v from a zero length array to an array of length 5. This makes the =[] part redundant.

EDIT:

The major difference here is that the Array constructor's prototype can be modified, so what you get in the end is not necessarily identical to a standard issue javascript Array.

When you assign using [], an internal constructor is used, which means Array prototype tampering will not affect your new object. For example, I can set Array.prototype.join=function(){alert("duh");} and all Arrays that you construct using new Array(...) will alert "duh" when you try to call the join method. Arrays assigned using [] are immune to this.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

No it is not necessary because both do the same thing. Basically all you should be doing is :

var v=[];  or var v=[value1, value2 ...];

The second version of defining an array has some issues like:

Array(4) ==> creates an empty 4-elements array

Array(4,5) ==> creates an array with 2 elements (4 and 5)

So if you want to create a 1 element array, it blows up in your face. Therefore, the first version is recommended.

Samson
  • 2,801
  • 7
  • 37
  • 55
0

The simple answer is that there's almost never a good reason to use the Array keyword in a declaration, whether that's:

var a = Array(n)

or

var a = new Array(n)

just use:

var a = [];

instead.

See https://stackoverflow.com/a/11500550/6782

Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

Its not necessary to use new with Array,i think you can create Array without using new operator

Heena Hussain
  • 3,673
  • 1
  • 20
  • 21
0

You are creating two Array objects and throwing away one, so what you are doing is not necessary.

Declare the variable and create an array:

var v;
v = new Array(5);

Or as a single statement:

var v = new Array(5);

The preferred way of creating arrays is using new Array when you want to specify a size, and an array literal when you want to create an array from items:

var a1 = new Array(42); // creates an array with 42 undefined items
var a2 = [1, 2, 3]; // creates an array with the 3 items

For a zero size array you can use either:

var a1 = new Array(); // creates an empty array
var a2 = []; // creates an empty array

The Array constructor can also take a list of items, but that use should be avoided because it behaves differently if there is one item and that item is numerical:

var a1 = new Array(100, 101, 102); // creates an array with three items
var a2 = new Array(100, 101); // creates an array with two items
var a3 = new Array(100); // creates an array with 100 undefined items
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • There's only one reason ever to use the Array constructor, that is to initialize the array with a bunch of undefineds, I've never had to do that, so I've always stayed away from that confusing constructor, the literal is so much nicer. if you really want to initialize it to a bunch of `undefined`s, I would use `var a = [];a.length = 100;` I think it's much clearer – Ruan Mendes Oct 24 '12 at 22:52
  • There's actually another reason (aside from the fact your way of doing it isn't convenient if you pass it as an argument to a function): laziness. `new Array( 10 ).map( function ( ) { return 1; } );` is an array containing 10 times `undefined`. `Array.apply( null, new Array( 10 ) ).map( function ( ) { return 1; } );` gives an array containing 10 ones. It's not efficient, bad etc. But it's fast to write and it works. So when you just want an array filled with some kind of data to test something, you can use that. – xavierm02 Oct 25 '12 at 19:36
-1

JavaScript - unlike most language - provides you arrays that kind of self-extend themselves when needed. But that doesn't mean it has no cost.

If you have an array of length N and put something at index M >= N, it has to create a new array of length M - 1, copy everything from N into it and then add your element, that's quite slow. Note that JavaScript has very diverse implementations and that some just consider arrays as normal objets with a special length property.

So to avoid that, when you know what size your array will be but not what it'll contain, you use new Array( size ). If you know what it will contain, it's better to use the litteral notation [ item1, item2 ]. And if you really don't know, just put [].

added

xavierm02
  • 8,457
  • 1
  • 20
  • 24
  • You don't know that what you're saying is true. Arrays in JS extend Object, so it's more likely that they are not contiguous, they are just maps, keyed by integers, with some code to find the maximum existing index to give you the `length`. – Ruan Mendes Oct 24 '12 at 22:59
  • I know what I'm saying and you don't. Implementing arrays as hashtables is ridiculous. And if they were, you would have the same performances on pop-push and unshift-shit. In a more mathematical way $A \implies B$. And here's a proof for $\neg B$ http://jsperf.com/so-push-pop-vs-unshift-shift – xavierm02 Oct 25 '12 at 17:38
  • The fact that you can do the same things doesn't mean it is implemented the same way. JS lets you do stupid things but doesn't optimize them. But interpreters do optimize things that are often used, e.g. interger keys in arrays... – xavierm02 Oct 25 '12 at 17:41
  • "it's more likely that they are not contiguous"... "more likely" seriously? It is "more likely" so you downvote without even checking? – xavierm02 Oct 25 '12 at 18:00
  • In IE7 they were not contiguous, they were just hash maps, IE improved its handling of arrays in IE8 http://blogs.msdn.com/b/jscript/archive/2008/03/25/performance-optimization-of-arrays-part-i.aspx My point is that you don't know how it's implemented and there's no guarantee, so you're guessing as much as I am and the behavior is subject to change. When you do `a = []; a[100] = 20` is that going to allocate 101 places in memory? not according to https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript#Arrays Current behavior is no guarantee. – Ruan Mendes Oct 25 '12 at 18:12
  • As ridiculous as it may sound, arrays were just hash tables initially in all JS implementations I'm aware of http://javascript.about.com/od/problemsolving/a/notarrays.htm. So you know what you're talking about and I don't huh? You are wrong that `shift/pop` should have the same performance, `unshift/shift` requires changing the index of all other elements in the array, `push/pop` doesn't. For fast contiguous arrays, you should use the well documented https://developer.mozilla.org/en-US/docs/JavaScript_typed_arrays Try being more polite and not such a jackass next time. – Ruan Mendes Oct 25 '12 at 18:22
  • IE doesn't count. It's JScript remember. – xavierm02 Oct 25 '12 at 18:29
  • And basically, what you're saying is "better not do it your way because it will improve only on some interpreters"... – xavierm02 Oct 25 '12 at 18:30
  • No, that's no what I'm saying, did you miss my point that your http://jsperf.com/so-push-pop-vs-unshift-shift example doesn't prove anthing? What I'm saying is if you want to prove your point, create a perfomance test that shows that starting an array with a given size is a lot faster than extending it dynamically. I'll take your comment that IE doesn't count (JScript is as much JavaScript as Chrome's implementation, they are all different from Mozilla's JavaScript implementation) as admission that your point is not very well made. – Ruan Mendes Oct 25 '12 at 18:37
  • JScript is officially another language. Or at least was. And it's known for being shitty. Check this one and tell me againt that arrays are implemented just like objects are: http://jsperf.com/are-arrays-hasmaps – xavierm02 Oct 25 '12 at 18:49
  • It could be that they just use a different hash function in firefox. But I'm quite sure there is more. – xavierm02 Oct 25 '12 at 18:50
  • Sorry, I don't see that your tests prove that arrays aren't implemented as objects, specially in the case of sparse arrays. SO is complaining about our chatting here, so I'm signing off, let other readers make up their own mind – Ruan Mendes Oct 25 '12 at 19:14
  • I was changing it when you looked so hadn't done the tests on firefox yet. But on firefox, there is a clear difference – xavierm02 Oct 25 '12 at 19:23
  • And that's my point, it's an implementation detail. – Ruan Mendes Oct 25 '12 at 19:24
  • It can't hurt to consider they are implemented like in "normal" languages. You gain performance on the interpreters where it is and don't loose anything on the others. – xavierm02 Oct 25 '12 at 19:26
  • "Normal" languages will waste space with a sparse array, there's some method to the madness of JavaScript arrays. You are better off understanding them than trying to apply premature optimization. Bye, really this time! – Ruan Mendes Oct 25 '12 at 19:35
  • If you have a sparse array, you more likely either need a hashmap or haven't indexed your items properly. Anyway, having a choice instead of being imposed a hashmap would be a good thing, I'll go ask why it is implemented that way. – xavierm02 Oct 25 '12 at 19:41