In most programming languages, A collection of a certain finite number of items is an Array. Or the Sets in the Mathematics.
In JavaScript as well, there are many ways to create arrays. We will be taking a look into some of them to create Arrays.
1 . Using assignment operator
var array = [];
var array2 = [1,2,3,4,5];
2. Using new operator
new Array(length)
- Creates an array with length set to the number.
length > 0
otherwise it will throw error
var arr = new Array(2);
arr; [empty × 2]
arr.length; // 2
arr[0]; undefined
// when we set
arr[3] = 10; //It will increase the array size
[empty × 3, 10]
3. Using Array.from
var arr = Array.from({length : 2});
arr; // [undefined, undefined]
arr[0] = 1; arr[1] = 2;
var arrCopy = Array.from(arr);
arrCopy; // [1,2]
4. Usign Spread operator
var arr = [1,2,3,4,5]
var array2 = [ ...arr ]
array2; // [1,2,3,4,5]
5. Using Array
Creates a new array with the arguments as items. The length of the array is set to the number of arguments.
var array = Array(1,2,3,4,5);
array; // [1,2,3,4,5]
6. Using Array.of
It is similar to Array constructor . But
- .
Array.of(5)
→[5]
Array(5)
→[empty x 5]
var array = Array.of(5);
array; / [5]
var array2 = Array.of(1,2,3,4,5,6, "string");
array2; // [1, 2, 3, 4, 5, 6, "string"]