Five ways to create an array in JavaScript
Beginner · 4 min read
An array is an ordered list of values, like the stops on a bus route or the scores in a game. Almost every program you write will build one, so it helps to know more than one way to make them. Each way fits a different starting point: values you type in, text you already have, or just a count.
In this tutorial you will build the same array, [1, 2, 3], five different ways. Then you will meet a small trap: Array(3) and Array.of(3) look alike but give you very different arrays. You only need to know what a variable and console.log are.
What "iterable" means
Several of the ways below take an iterable. That is anything JavaScript can walk through one item at a time: an array, a string (one character at a time), a Set or a Map. If you can loop over it with for...of, it is iterable.
for (const ch of '123') console.log(ch); // prints 1, then 2, then 3
A plain object like { a: 1 } is not iterable. Keep that in mind for later exercises.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
1 Five ways to build an array
easyProduce [1, 2, 3] five different ways. Then explain why Array(3) and Array.of(3) are not the same thing.
Stuck? Three hints, smallest first
- 1. A literal,
Array.of,Array.from, spreading an iterable, andArray.from({ length: n }, mapper). - 2.
Array(3)reads its single number as a length.Array.of(3)reads it as a value. - 3. An array built from a length has holes in it, not zeros, and not
undefinedvalues.
Step 1: a literal
The simplest way is to write the values between square brackets. This is called an array literal.
const literal = [1, 2, 3];
console.log(literal); // [ 1, 2, 3 ]
Use this whenever you know the values while you are writing the code.
Step 2: Array.of
Array.of takes any number of values and puts them in a new array, in order.
const listed = Array.of(1, 2, 3);
console.log(listed); // [ 1, 2, 3 ]
It looks like extra typing for the same result. Step 6 shows why it exists.
Step 3: Array.from with a string
Array.from copies any iterable into a new array. You can also give it a second argument, a function that changes each item as it is copied.
console.log(Array.from('123')); // [ '1', '2', '3' ]
const mapped = Array.from('123', Number);
console.log(mapped); // [ 1, 2, 3 ]
Without the second argument you get three strings. Number turns each one into a real number on the way in.
Step 4: spread an iterable
The spread syntax, three dots, unpacks an iterable inside square brackets. A Set keeps only one copy of each value, so the second 3 disappears.
const spread = [...new Set([1, 2, 3, 3])];
console.log(spread); // [ 1, 2, 3 ]
Step 5: a length and a function
Often you don't have values yet, only a count. Array.from({ length: 3 }, fn) makes an array of that length and calls your function once for each slot. The function receives the current value (here always undefined, so we name it _) and the index, starting at 0.
const counted = Array.from({ length: 3 }, (_, i) => i + 1);
console.log(counted); // [ 1, 2, 3 ]
i + 1 turns the indexes 0, 1, 2 into 1, 2, 3. Change the function and you can build any sequence you like.
Step 6: the Array(3) trap
You might expect Array(3) to make an array holding the number 3. It doesn't.
const sized = Array(3);
const single = Array.of(3);
console.log(sized.length); // 3
console.log(single); // [ 3 ]
console.log(single.length); // 1
When Array gets exactly one number, it treats it as a length. You get an array of length 3 with nothing in it. Array.of(3) always treats its arguments as values, so you get one slot holding 3. That difference is the reason Array.of was added.
Step 7: holes are not values
The three slots in Array(3) are holes: empty places with nothing stored. The in operator asks "is there something stored at this index?".
const sized = Array(3);
console.log(0 in sized); // false: nothing at index 0
console.log(sized[0]); // undefined
console.log(JSON.stringify(sized)); // [null,null,null]
Reading a hole gives undefined, and JSON.stringify prints holes as null, so they are easy to mistake for real values. They are not. Methods like map and forEach skip holes completely, which is why Step 5's Array.from is the safer way to build from a length: every slot gets a real value.
The full solution
The panel builds all five arrays, then puts Array(3) and Array.of(3) side by side. Press Run to see the output and the checks.
const literal = [1, 2, 3];
const listed = Array.of(1, 2, 3);
const mapped = Array.from('123', Number); // a string is iterable
const spread = [...new Set([1, 2, 3, 3])]; // any iterable will do
const counted = Array.from({ length: 3 }, (_, i) => i + 1);
// The single-argument constructor is the trap. One number means a length.
const sized = Array(3);
const single = Array.of(3);
console.log('literal :', literal);
console.log('of :', listed);
console.log('from :', mapped);
console.log('spread :', spread);
console.log('counted :', counted);
console.log('--- Array(3) against Array.of(3) ---');
console.log('Array(3) :', sized, 'length', sized.length);
console.log('Array.of(3) :', single, 'length', single.length);
console.log('is index 0 present in Array(3)?', 0 in sized, '<- a hole, not a value');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a literal', literal, [1, 2, 3]);
test('Array.of takes values', listed, [1, 2, 3]);
test('Array.from maps as it copies', mapped, [1, 2, 3]);
test('spreading an iterable', spread, [1, 2, 3]);
test('a length plus a mapper', counted, [1, 2, 3]);
test('Array(3) is three empty slots', sized.length, 3);
test('Array.of(3) is one slot holding 3', single, [3]);
test('nothing is stored at index 0 of Array(3)', 0 in sized, false);
test('though JSON prints the holes as null', JSON.stringify(sized), '[null,null,null]');
Array.of exists solely because of the last three assertions. Array(3) gives you a length-3 array with nothing in it, while Array(3, 4) gives you two elements — one argument means a length, two or more mean values, and that inconsistency is why Array.of was added.
Array.from({ length: n }, mapper) is the workhorse. It is the one build that produces real values in every slot, which matters because holes are skipped by map and forEach later on.
Common mistakes
- Writing
Array(3)to mean[3]. One number means a length. Use[3]orArray.of(3). - Calling
maponArray(5).Array(5).map((_, i) => i)still has five holes, becausemapskips them. UseArray.from({ length: 5 }, (_, i) => i). - Trusting
JSON.stringifyto show holes. It prints them asnull, so an empty array of length 3 looks like it holds three nulls.
Try it yourself
- Build
[0, 2, 4, 6, 8]withArray.from({ length: 5 }, ...). - Turn the string
'2024'into the array[2, 0, 2, 4]in one line. - What do
Array(2, 3)andArray.of(2, 3)give? Predict, then check withconsole.log.