There are multiple ways to declare an empty array in JavaScript. The below code is the simplest way when all you need is only an empty array. Just assign an empty bracket to it.
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.
JavaScript declares an empty array
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>
Output:
Both methods achieve the same result of creating an empty array. You can then add elements to the array using various methods such as push()
, unshift()
, or by directly assigning values to specific indices.
const myArray = [];
myArray.push("apple");
myArray.push("banana");
myArray.push("orange");
console.log(myArray); // Output: ["apple", "banana", "orange"]
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
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 = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == 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.
Source: stackoverflow.com/
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