Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Mutating vs Non-Mutating Methods

JavaScript’s array methods fall into two categories. The distinction matters in surface Lykn, where immutability is the default.

Non-Mutating (Preferred)

MethodPurpose
mapTransform each element
filterSelect matching elements
sliceExtract a sub-array
concatCombine arrays
flat / flat-mapFlatten nested arrays
to-sortedSort (ES2023, non-mutating)
to-reversedReverse (ES2023, non-mutating)
to-splicedSplice (ES2023, non-mutating)
withReplace at index (ES2023)

These return new arrays. The original is unchanged.

Mutating (Use with Care)

MethodPurpose
push / popAdd/remove at end
shift / unshiftAdd/remove at start
sortSort in place
reverseReverse in place
spliceInsert/remove at index
fillFill with value

These change the array in place. In surface Lykn, use them inside swap! on cell-wrapped arrays, or on arrays that aren’t shared.

The Lykn Way: conj

For immutable append:

(bind extended (conj items new-item))
const extended = [...items, newItem];

conj is spread-based — it creates a new array. For multiple additions, concat or reduce is more efficient than repeated conj (each conj copies the entire array).

The ES2023 Non-Mutating Variants

to-sorted, to-reversed, to-spliced, and with are JavaScript’s own answer to the mutation problem. They do what their mutating counterparts do, but return new arrays:

(bind sorted (nums:to-sorted))
(bind reversed (nums:to-reversed))
(bind replaced (nums:with 2 99))     ;; replace index 2 with 99

These are the methods Lykn’s functional style prefers. Use them over the mutating versions wherever possible.