Six ways to create an Array in JavaScript.

Learn Different ways to create JavaScript Arrays.

Javascript Jeep🚙💨
Nov 30 · 2 min read
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.
var arr = new Array(2);arr; [empty × 2]arr.length; // 2arr[0]; undefined// when we setarr[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]
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

JavaScript in Plain English

Learn the web's most important programming language.

Javascript Jeep🚙💨

Written by

Articles related to javascript

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade