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.