const fruits =["apple","banana","cherry"];const range =Array.from({ length:5},(_, i)=> i +1);console.log(range);// [1, 2, 3, 4, 5]const filled =newArray(3).fill(0);console.log(filled);// [0, 0, 0]
Note Array(5) creates 5 empty slots, not [5]. Use Array.of(5) for a single-element array. Be careful with fill() on objects -- all slots share the same reference.
Note Works on Arrays, Strings, and TypedArrays. The main advantage over bracket notation is support for negative indices.
Frequently asked questions
How does JavaScript handle array at?
JavaScript covers this with 4 copy-ready snippets on this page. The "Creating Arrays" snippet in JavaScript uses `const arr = [a, b, c];`.
Which code does the JavaScript example use?
The "Creating Arrays" snippet uses `const arr = [a, b, c];`, from the Arrays section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "array at"?
Besides "Creating Arrays", this page also shows "Accessing Elements", "Non-Mutating Alternatives (ES2023)", "Array/String .at() Method".
Is there anything to watch out for?
Yes. For "Creating Arrays": Array(5) creates 5 empty slots, not [5]. Use Array.of(5) for a single-element array. Be careful with fill() on objects -- all slots share the same reference.