I would like to add the speed issue - the current fastest way, on google chrome is the second one.
But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.
For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on chrome, but if you'd try it on mozilla dev. you'd get a surprisingly higher rate of 23 million.
Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such
There is a difference, but there is no difference in that example.
Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
For more information, the following page describes why you never need to use new Array()
You never need to use new Object() in
JavaScript. Use the object literal {}
instead. Similarly, don’t use new Array(),
use the array literal []
instead. Arrays in JavaScript work
nothing like the arrays in Java, and
use of the Java-like syntax will
confuse you.
Do not use new Number, new String, or
new Boolean. These forms produce
unnecessary object wrappers. Just use
simple literals instead.
Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).
The difference of using
Or
As been discussed enough in this question.
I would like to add the speed issue - the current fastest way, on
google chrome
is the second one.But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.
For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on
chrome
, but if you'd try it onmozilla dev.
you'd get a surprisingly higher rate of 23 million.Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such
There is a difference, but there is no difference in that example.
Using the more verbose method:
new Array()
does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:To illustrate the different ways to create an array:
For more information, the following page describes why you never need to use
new Array()
Also check out the comments - the
new Array(length)
form does not serve any useful purpose (at least in today's implementations of JavaScript).