iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Arrays

An array is an ordered, zero-indexed list. Arrays are objects under the hood but come with a rich set of methods for transformation, search, and iteration.

Creating and accessing

JS
const fruits = ["apple", "banana", "cherry"];

fruits[0]            // "apple"
fruits.length        // 3
fruits[fruits.length - 1]   // "cherry" (last item)
fruits.at(-1)        // "cherry" — modern equivalent

The methods you'll use weekly

MethodMutates?What it does
push / popYesAdd / remove from the end.
unshift / shiftYesAdd / remove from the beginning.
splice(i, n, …)YesRemove and/or insert in the middle.
slice(i, j)NoReturn a copy of a sub-range.
map(fn)NoBuild a new array by transforming each item.
filter(fn)NoNew array of items that pass a test.
reduce(fn, init)NoBoil items down to a single value.
find / findIndexNoFirst matching item / index.
some / everyNoAny / all items pass a test (returns boolean).
includes(x)NoIs x in the array?
sort(cmp)YesSort in place. Pass a comparator for numeric sort.
join(sep)NoCombine items into a string.

Common pipelines

JS
const cart = [
  { name: "Apples",  price: 2,  qty: 3 },
  { name: "Bananas", price: 1,  qty: 6 },
  { name: "Cookies", price: 4,  qty: 1 },
];

// Total cost
const total = cart.reduce((t, item) => t + item.price * item.qty, 0); // 16

// Names of items costing > $1 each
const expensive = cart.filter(i => i.price > 1).map(i => i.name);

// Sort cheapest first (numeric, ascending)
const sorted = [...cart].sort((a, b) => a.price - b.price);
Tip: Default to non-mutating methods (map, filter, slice, spread). They make state changes obvious and play nicely with most modern frameworks.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Arrays!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Build a new array with each number doubled.

const doubled = nums. (n => n * 2);

Test yourself

Q1. Which method does NOT mutate the array?
Q2. Sum an array with…
Q3. Get the last element with…

Discussion

Loading…