JavaScript Arrays: Creating Arrays with Literals, Spread, Array.of and Array.from
What JavaScript arrays are (ordered, untyped, dynamic, objects with numeric keys) and every way to create one: literals, holes and trailing commas, spread from any iterable, the Array() constructor and its traps, Array.of, Array.from with a mapping function, ranges, 2D grids and Array.fromAsync.
kvi5hnuCode Sprout team member6 min readOn this page
An array is an ordered list of values. Each value is an element, and each element has a numeric position, its index, starting at 0. Arrays are everywhere: lists of users from an API, rows of a table, characters of a string, results of a search.
JavaScript arrays have a few characteristics worth knowing up front:
- Untyped: one array can hold numbers, strings, objects, other arrays and functions together.
- Dynamic: they grow and shrink as you add and remove elements; you never declare a size.
- Zero-based, with a maximum length of 2³² − 1 (about 4.3 billion).
- They're objects. An array is an object whose property names happen to be indexes, plus a special
lengthproperty and many methods inherited fromArray.prototype. Engines optimize them heavily, so element access is fast. - They can be sparse: there can be gaps with no element at all (next article).
const mixed = [42, "text", true, null, { id: 1 }, [1, 2], () => "hi"];
console.log(mixed.length, typeof mixed, Array.isArray(mixed));
7 object true
typeof says "object" for arrays, so use Array.isArray(value) to test for one.
For fixed-size arrays of numbers with a fixed element type, such as image pixels or audio samples, JavaScript also has typed arrays (Uint8Array, Float64Array, ...), covered in part 11.
Array literals
The usual way to create an array is a literal: values in square brackets, separated by commas. The values can be any expressions:
const empty = [];
const primes = [2, 3, 5, 7];
const start = 100;
const block = [start, start + 1, start + 2];
const points = [[0, 0], { x: 3, y: 4 }]; // arrays and objects nest freely
console.log(empty.length, primes[2], block, points[1].y);
0 5 [ 100, 101, 102 ] 4
Like object literals, an array literal creates a new array every time it's evaluated.
Trailing commas and holes
A trailing comma after the last element is allowed and ignored. Two commas in a row with nothing between them create a hole: a position with no element at all:
const trailing = [1, 2, 3,];
const withHole = [1, , 3];
console.log(trailing.length, withHole.length, 1 in withHole, withHole[1]);
console.log([, ,]);
3 3 false undefined
[ <2 empty items> ]
Reading a hole gives undefined, but the element doesn't exist (1 in withHole is false), and some array methods skip it. Holes are almost always accidental; ESLint's no-sparse-arrays flags them. [, ,] has length 2, not 3, because the last comma is a trailing comma.
Spread: elements from any iterable
...iterable inside an array literal inserts all of the iterable's values at that position (ES2015):
const middle = [2, 3];
console.log([1, ...middle, 4, ...middle]);
console.log([..."héllo👋"]); // characters, by code point
console.log([...new Set([3, 1, 3, 2, 1])]); // remove duplicates
console.log([...new Map([["k", 1]])]); // [key, value] pairs
[ 1, 2, 3, 4, 2, 3 ]
[ 'h', 'é', 'l', 'l', 'o', '👋' ]
[ 3, 1, 2 ]
[ [ 'k', 1 ] ]
Spread works with iterables: arrays, strings, Sets, Maps, generators, arguments, DOM NodeLists. A plain object isn't iterable, so [...{ a: 1 }] throws a TypeError (use Object.values or Object.entries).
[...new Set(array)] is the idiomatic one-liner for removing duplicate values (strict equality, except that NaN matches NaN), keeping first occurrences in order.
Copying an array
[...original] creates a shallow copy: a new array with the same elements. original.slice() and Array.from(original) do the same thing:
const original = [[1], [2]];
const copy = [...original];
copy.push([3]); // only the copy grows
copy[0].push(99); // but the inner arrays are shared
console.log(original, copy.length);
[ [ 1, 99 ], [ 2 ] ] 3
For nested data, use structuredClone(original) (article 21).
The Array() constructor and its trap
new Array(...) (or just Array(...), which behaves the same) does different things depending on its arguments:
console.log(new Array()); // no arguments: empty
console.log(new Array(3)); // ONE number: a length, with no elements
console.log(new Array(3, 4)); // anything else: the elements
console.log(new Array("3")); // one non-number: an element
for (const bad of [-1, 2.5]) {
try {
new Array(bad);
} catch (err) {
console.log(bad, err.name);
}
}
[]
[ <3 empty items> ]
[ 3, 4 ]
[ '3' ]
-1 RangeError
2.5 RangeError
new Array(3) creates an array of length 3 with three holes, not three undefineds. That matters, because methods like map and forEach skip holes:
console.log(Array(3).map(() => 0));
console.log(Array(3).fill(0));
[ <3 empty items> ]
[ 0, 0, 0 ]
Because of these surprises, prefer literals, and when you need "n copies of a value", use Array(n).fill(value) or Array.from (below).
Array.of
Array.of(...items) (ES2015) always treats its arguments as elements, even a single number. It fixes the constructor's one-number special case:
console.log(Array.of(3), Array.of(1, 2, 3), Array.of());
[ 3 ] [ 1, 2, 3 ] []
It's mainly useful when you pass an unknown list of values to a function that creates arrays. In everyday code a literal [3] does the same thing.
Array.from
Array.from(source, mapFn?) (ES2015) creates a new array from an iterable or an array-like object (anything with a length and indexed properties), optionally transforming each element as it goes:
console.log(Array.from("abc"));
console.log(Array.from(new Set([1, 1, 2])));
console.log(Array.from({ length: 2, 0: "x", 1: "y" })); // array-like
console.log(Array.from([1, 2, 3], (n) => n * 10)); // with a mapping function
[ 'a', 'b', 'c' ]
[ 1, 2 ]
[ 'x', 'y' ]
[ 10, 20, 30 ]
Array-likes appear in older APIs: the arguments object, HTMLCollection from getElementsByClassName, and DOM NodeList in very old browsers. Converting them with Array.from gives you all the array methods.
The mapping function receives (element, index). That makes Array.from({ length: n }, fn) the standard way to generate arrays:
console.log(Array.from({ length: 5 }, (_, i) => i + 1)); // a range 1..5
console.log(Array.from({ length: 4 }, (_, i) => 2 ** i)); // powers of two
console.log([...Array(5).keys()]); // 0..4, another idiom
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 4, 8 ]
[ 0, 1, 2, 3, 4 ]
The _ is a common name for a parameter you don't use. { length: 5 } is an array-like with no elements, so the first argument is always undefined; only the index matters.
Building a 2D grid
A classic mistake when creating a grid (a board game, a matrix, a seating plan) is to fill the outer array with one row:
![Array(2).fill(row) puts the same row object in both slots, so changing grid[0][0] also changes grid[1][0]; Array.from with a function creates a separate row for each slot](https://code-sprout-content.laxmi.solutions/asset/2026/11/js-array-fill-shared-rows-fypobgtuy2tcrwk3.png)
const shared = Array(2).fill(Array(3).fill(0));
shared[0][0] = 1;
console.log(shared);
const grid = Array.from({ length: 2 }, () => Array(3).fill(0));
grid[0][0] = 1;
console.log(grid);
[ [ 1, 0, 0 ], [ 1, 0, 0 ] ]
[ [ 1, 0, 0 ], [ 0, 0, 0 ] ]
fill(value) stores the same value in every slot, and for an object, that's the same reference (article 21). Array.from's function runs once per slot and creates a fresh row each time.
Array.fromAsync
Array.fromAsync(source) (ES2026, though engines shipped it in 2024) is the asynchronous version: it consumes an async iterable, such as an async generator or a stream, and returns a promise of an array:
async function* pages() {
yield "page 1";
yield "page 2";
}
Array.fromAsync(pages()).then((all) => console.log(all));
[ 'page 1', 'page 2' ]
Part 13 covers async iteration.
Which to use?
| You want | Use |
|---|---|
| Specific values | literal [a, b, c] |
| Combine arrays or add elements | spread [...a, x, ...b] |
| An array from a string, Set, Map, generator | [...iterable] or Array.from(iterable) |
An array from an array-like (arguments, old DOM lists) | Array.from(arrayLike) |
| n copies of a primitive | Array(n).fill(value) |
| n generated values, or n separate objects | Array.from({ length: n }, (_, i) => ...) |
| A shallow copy | [...arr], arr.slice() or Array.from(arr) |
Common questions
Should I ever use new Array()?
Rarely. new Array(n) is occasionally used to preallocate a length, but holes make the result behave oddly, and modern engines grow arrays efficiently anyway. Literals, fill and Array.from cover practically everything.
Spread or Array.from?
Both work for iterables. Use spread for short expressions and for combining arrays; use Array.from for array-likes (spread can't handle those) and when you want the built-in mapping function.
How do I create an array of numbers from a to b?
Array.from({ length: b - a + 1 }, (_, i) => a + i)
There's a proposal for a built-in Iterator.range, but it isn't standard yet.
Why is Array.isArray needed when instanceof Array exists?
instanceof fails for arrays created in another realm, such as an iframe or a Node vm context, because they inherit from a different Array.prototype. Array.isArray works everywhere.
Summary
- Arrays are ordered, untyped, dynamic, zero-based objects with a special
length; test for them withArray.isArray. - Literals
[...]create new arrays each time; trailing commas are fine, double commas make holes. - Spread
[...iterable]copies or combines anything iterable;[...new Set(arr)]removes duplicates. new Array(n)with one number makesnholes; other arguments become elements; prefer literals.Array.ofalways treats arguments as elements.Array.from(source, mapFn)converts iterables and array-likes and generates arrays with{ length: n }; use it for grids so each row is a separate array.Array.fromAsynccollects an async iterable into an array.
Practice Questions
What are the lengths of [,], [1,], [1,,] and [,1]?
Answer
1, 1, 2 and 2. A single trailing comma is ignored; every other comma separates a position, possibly a hole.
Create ["#0", "#1", "#2"] without writing a loop.
Answer
Array.from({ length: 3 }, (_, i) => `#${i}`) or [...Array(3).keys()].map((i) => "#" + i).
What does this code return, and why?
new Array(2).map((_, i) => i)
Answer
[ <2 empty items> ]. new Array(2) has holes, and map skips holes, so the callback never runs. Use Array.from({ length: 2 }, (_, i) => i).
Remove duplicates from ["b", "a", "b", "c", "a"], keeping the first occurrence order.
Answer
[...new Set(["b", "a", "b", "c", "a"])] gives [ 'b', 'a', 'c' ]. A Set keeps values in insertion order and ignores repeats.
Previous: JavaScript Getters and Setters: Accessor Properties, Validation and Computed Values
Next: JavaScript Array Elements: Indexes, length, at(), Sparse Arrays, Adding and Removing

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.