How to Create an Array in JavaScript | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
JavaScript

How to Create an Array in JavaScript

Learn different ways to create and initialize arrays in JavaScript.

JavaScriptArraysData Structures

Arrays are fundamental data structures in JavaScript for storing ordered collections of items.

The most common and preferred way:

// Empty array
const emptyArray = [];

// Array with items
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null];

console.log(fruits); // ["apple", "banana", "cherry"]

Method 2: Array Constructor

Using the Array constructor:

// Empty array with specific length
const arr = new Array(5);
console.log(arr.length); // 5

// Array with items
const colors = new Array("red", "green", "blue");
console.log(colors); // ["red", "green", "blue"]

Method 3: Array.of()

Creates an array from arguments:

const nums = Array.of(1, 2, 3);
console.log(nums); // [1, 2, 3]

// Useful for single number (unlike Array constructor)
const single = Array.of(5);
console.log(single); // [5] (not an empty array of length 5)

Method 4: Array.from()

Create arrays from iterables or array-like objects:

// From a string
const chars = Array.from("hello");
console.log(chars); // ["h", "e", "l", "l", "o"]

// With a mapping function
const squares = Array.from([1, 2, 3], x => x * x);
console.log(squares); // [1, 4, 9]

// Create a range
const range = Array.from({length: 5}, (_, i) => i);
console.log(range); // [0, 1, 2, 3, 4]

Method 5: Spread Operator

Copy or combine arrays:

const original = [1, 2, 3];
const copy = [...original];

const combined = [...[1, 2], ...[3, 4]];
console.log(combined); // [1, 2, 3, 4]

Method 6: fill()

Create an array filled with a value:

const zeros = new Array(5).fill(0);
console.log(zeros); // [0, 0, 0, 0, 0]

const repeated = new Array(3).fill("hello");
console.log(repeated); // ["hello", "hello", "hello"]

Summary

  • Use [] array literals for most cases
  • Use Array.from() to convert iterables or create ranges
  • Use Array.of() when you need predictable behavior with single values
  • Use fill() to initialize arrays with a specific value