javascript tutorial - [Solved-5 Solutions] Difference between “array()” and “[]” while declaring a javascript array - javascript - java script - javascript array
Problem:
What's the real difference between declaring an array like this:
and
Solution 1:
- 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 we pass a number to the constructor, we will get an array of that length:
To illustrate the different ways to create an array:
Solution 2:
- The difference between creating an array with the implicit array and the array constructor is subtle but important.
- When we create an array using
- You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.
- If we use:
- You're telling the interpreter, we want to call the constructor "Array" and generate an object. It then looks up through our execution context to find the constructor to call, and calls it, creating our array.
- We may think "Well, this doesn't matter at all. They're the same!". Unfortunately we can't guarantee that.
- Take the following example:
- In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. We will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.
- While we may expect this to happen, it just illustrates the fact that [] is not the same as new Array().
- It's probably best to just use [] if we know we just want an array. We also do not suggest going around and redefining Array...
Solution 3:
Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if we know the approximate size of the array. If we add more items than the length you've given, the performance boost is lost.
Solution 4:
The first one is the default object constructor call. We can use it's parameters if we want.
The second one gives we the ability to create not empty array:
Solution 5:
In order to better understand [] and new Array():
The above result is from Google Chrome console on Windows 7.