var arrayName = ;
If you know the expected length of the array and where all the elements are undefined.
var arrayName = new Array(expectedLength); var product_arr = new Array(); //declaring empty array
Note: if you check the length of the array, the output will be ‘expected length’ while in the first implementation it would be 0.
Simple example code.
<!DOCTYPE html> <html> <body> <script> var arr = ; console.log(arr.length) var newArr = new Array(5); console.log(newArr.length) </script> </body> </html>
Answer: 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 =  // e.length == 1, e == 3 f = new Array(3), // f.length == 3, f == undefined
Another difference is that when using
new Array() you’re able to set the size of the array, which affects the stack size. The
new Array(5) will not actually add five
undefined items to the array. It simply adds space for five items. Be aware that using
Array this way makes it difficult to rely on
array.length for calculations.
Do comment if you have any doubts or suggestions on this JS array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.