Six ways to create an Array in JavaScript.

Learn Different ways to create JavaScript Arrays.

Image by Clem Onojeghuo

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]

If we pass single number argument , then the Array constructor will create a new Array of the length equivalent to the argument

var array= Array(5);
array; //[empty x 5]

If we pass string

var array= new Array("5");
array; ["5"]

To create a Array with single number elemennt , we can use Array.of

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"]

Follow me JavaScript Jeep🚙💨 .

Buy me a coffee.

Buy me a coffee

Other articles

View at Medium.com

Leave a comment

Design a site like this with WordPress.com
Get started