Array at

4 snippets in JavaScript

Also written as array with · Array.from

JSJavaScript

Creating Arrays

JS · Arrays
Syntax
const arr = [a, b, c];
const arr = Array.from(iterable);
const arr = Array.of(elements);
Example
const fruits = ["apple", "banana", "cherry"];
const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range);  // [1, 2, 3, 4, 5]

const filled = new Array(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.

Accessing Elements

JS · Arrays
Syntax
arr[index]
arr.at(index)
Example
const colors = ["red", "green", "blue", "yellow"];
console.log(colors[0]);     // "red"
console.log(colors.at(-1));  // "yellow"
console.log(colors.at(-2));  // "blue"

Note at() supports negative indexing. Bracket notation with negatives (arr[-1]) returns undefined because it looks for a property named "-1".

Non-Mutating Alternatives (ES2023)

JS · Arrays
Syntax
arr.toSorted(fn)
arr.toReversed()
arr.toSpliced(start, deleteCount, ...items)
arr.with(index, value)
Example
const original = [3, 1, 4, 1, 5];

const reversed = original.toReversed();
console.log(reversed);  // [5, 1, 4, 1, 3]

const replaced = original.with(2, 99);
console.log(replaced);  // [3, 1, 99, 1, 5]

console.log(original);  // [3, 1, 4, 1, 5] (untouched)

Note These return new arrays, leaving the original unchanged. Ideal for immutable state patterns (React, Redux, etc).

Array/String .at() Method

JS · Modern Features
Syntax
arr.at(index)
str.at(index)
Example
const stack = ["first", "second", "third", "last"];
console.log(stack.at(0));   // "first"
console.log(stack.at(-1));  // "last"
console.log(stack.at(-2));  // "third"

console.log("hello".at(-1)); // "o"

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.