Stop hand-rolling for loops: array methods, explained plainly
The menu is a list of dishes and the orders are a list of things already ordered — prices, allergen filters, and sales sorting are all array work. This guide follows MDN's Indexed collections guide: array creation traps, mutating vs non-mutating methods, map and filter, find and reduce, flat and groupBy, empty slots, and array-like objects.

First, the boundaries of this guide. The site already has a practical guide to Promises and async/await, about the ways to write code that waits for a result to come back; a practical guide to the event loop, about the order code runs in; and a practical guide to closures and scope, about who can see a variable. This guide is about none of those. It is about one thing only: you have a list of things, and you want to turn it into the shape you need with array methods. Used well, array methods cut list code in half and make it twice as readable. The "Greenstone Cafe" used below is still the same fictional practice project: a small web tool that takes orders for a street-side cafe. This time it is about its menu and order lists: the menu is a list of dishes, the orders are a list of things already ordered, and working out prices, filtering allergens, and sorting by sales are all array work. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. All syntax and behavior of arrays comes from MDN's Indexed collections guide; see each article's meta information and evidence record for sources. MDN's own examples, such as the three strings Wind, Rain, and Fire, the inventory list with asparagus, and the cats array, are the documentation's examples, not real user data.
Step 1: Build arrays with brackets first — Array(42) does not hold one 42
The steadiest way to build an array is the bracket literal: const arr3 = [element0, element1, elementN]. MDN puts it plainly: the bracket syntax is called an array literal, it is shorter than the other forms of array creation, and so it is generally preferred. You can also write new Array or call Array() directly with the same effect, but there is a big trap: passing a single number does not mean "hold this one number", it means "make the length this number". MDN's example is: const arr = [42] gives an array holding only the number 42, while const arr = Array(42) gives an array of length 42 holding no elements at all. Worse still, passing a number with a fractional part throws outright: Array(9.3) throws a RangeError: Invalid array length, because a length cannot be 9.3.
To safely hold a single element of any type, even a number, there are two ways: brackets, [9.3], or Array.of(9.3), which is MDN's own example — the array holds only 9.3. The cafe's menu price list stepped into this trap: wanting an array holding just the price 42, it wrote Array(42), and the list page rendered 42 empty slots with every price undefined. Remember the first sentence: build arrays with brackets by default; for a single number element, use Array.of, never Array().
Step 2: Indexes start at 0, and length is always the highest index plus 1
JavaScript array indexes start at 0, not at 1. MDN's example is: const myArray = ["Wind", "Rain", "Fire"], the first element is myArray[0], the second is myArray[1]. The length property is special: its value is always one more than the highest index stored. MDN's cats example is: const cats = [], cats[30] = ["Dusty"], and now cats.length is 31, because the highest index is 30. Positions 0 through 29 are all empty slots.
length is not only readable, it is writable. Writing a value shorter than the number of stored items truncates the array; writing 0 empties it entirely. MDN's example is: cats is ["Dusty", "Misty", "Twiggy"], length 3; after cats.length = 2 the array is ["Dusty", "Misty"] and Twiggy is gone; after cats.length = 0 the array is []; and setting cats.length to 3 again gives 3 empty items — not three undefined values. Empty slots and undefined are two different things, and step 11 explains them in detail. The cafe's order-list clear button uses exactly this: orders.length = 0 clears everything in one line, faster and cleaner than popping items one by one.
There is one more rule about indexes that is easy to miss: an index has to be an integer. MDN's example is: arr is [], and writing arr[3.4] = "Oranges" leaves the array's length at 0, because 3.4 is not an index — JavaScript simply attaches an ordinary property named 3.4 to the array object, and Object.hasOwn(arr, 3.4) reads back true. In other words, an array is an ordinary object underneath, and an index is just one kind of property name; only integer indexes count as elements, and anything else hung on it is a property that does not count toward length and is never visited by forEach, map, and the other methods. When debugging, if an array "clearly has things in it but its length is 0", first check whether someone wrote to it with a fractional index or attached some other property name.
Step 3: push, pop, shift, unshift — first tell which end, then what they return
The four most used methods for adding and removing items are push, pop, shift, and unshift. First tell which end they touch: push and pop work on the tail, shift and unshift on the head. Then tell what they return: push returns the new length of the array after adding, pop returns the last element that was removed, shift returns the first element that was removed, and unshift returns the new length after adding. MDN's examples work it out plainly: myArray is ["1", "2"], and push("3") makes it ["1", "2", "3"]; myArray is ["1", "2", "3"], and pop() takes "3", leaving ["1", "2"]; shift() takes "1", leaving ["2", "3"]; unshift("4", "5") makes the array ["4", "5", "1", "2", "3"].
The return value is what beginners mix up most: push returns the length, not the array itself, so writing myArray = myArray.push("3") turns the array into the number 3 and destroys the whole list. The cafe's order page stepped into this trap: when adding a dish it wrote orders = orders.push(dish), orders became 1, and the next add crashed. Remember the test: push and unshift return the length, pop and shift return the removed element; if you want the new array, do not take the return value — just keep using the original array.
Step 4: concat, join, slice, at — four helpers that leave the original alone
Not every array method changes the original. concat, join, slice, and at are all "look and leave, touch nothing". concat joins two or more arrays and returns a new one: in MDN's example myArray is ["1", "2", "3"], and concat("a", "b", "c") gives ["1", "2", "3", "a", "b", "c"], with the original untouched. join joins all elements into a string: ["Wind", "Rain", "Fire"].join(" - ") gives "Wind - Rain - Fire", which is how the menu's dish list is shown as one line of text.
slice cuts out a section and returns a new array: in MDN's example ["a", "b", "c", "d", "e"].slice(1, 4) gives ["b", "c", "d"], starting at index 1 and stopping before index 4 — head included, tail excluded — while the original keeps all five elements. at reads by index and is made for counting from the end: myArray.at(-2) is the second-last element "d", and going out of range returns undefined instead of throwing. The cafe's "latest three orders" is written this way: orders.slice(-3), no length math, no fear of going out of range, one line and done.
Step 5: splice, reverse, sort — these three change in place, so beware of friendly fire
Opposite to the four above, splice, reverse, and sort change in place: they modify the original array, and what they return is incidental. splice removes a section and optionally inserts replacements: in MDN's example myArray is ["1", "2", "3", "4", "5"], splice(1, 3, "a", "b", "c", "d") starts at index 1, removes 3 elements, inserts a, b, c, d in their place, the array becomes ["1", "a", "b", "c", "d", "5"], and the return value is the removed ["2", "3", "4"]. reverse transposes in place: ["1", "2", "3"].reverse() becomes ["3", "2", "1"], and the return value is the same array again.
sort is the easiest to trip over: by default it sorts as strings, not as numbers. MDN's example is ["Wind", "Rain", "Fire"].sort() becoming ["Fire", "Rain", "Wind"], sorted alphabetically. If the array holds numbers, [10, 9, 80].sort() with no compare function sorts as strings into [10, 80, 9], because "10" is smaller than "80" and "80" is smaller than "9". MDN's rule for the compare function is: the callback returns a negative number when a comes before b, a positive number when a comes after b, and zero when the two are considered equivalent and keep their original order. In MDN's last-letter example, sortFn compares the last character of a and b, and ["Wind", "Rain", "Fire"] comes out as ["Wind", "Fire", "Rain"]. The cafe's menu sorted by price must be written (a, b) => a.price - b.price; forget the compare function and a 42-yuan dish sorts ahead of a 9-yuan one, which any customer spots at once.
Step 6: forEach — run through each item once, but it returns nothing
forEach is the most direct iteration method: give it a callback and it runs it once for every item in the array. MDN's example is: colors is ["red", "green", "blue"], colors.forEach((color) => console.log(color)), printing red, green, and blue in turn. The callback receives the current element each time, and can also receive the index and the whole array, but forEach always returns undefined — it is not for building a new array, it is for "doing something to each item", such as rendering a list, writing a log, or sending a request.
Two more things to remember. First, forEach skips empty slots: in a sparse array the callback simply never runs for the unfilled positions, as step 11 explains in detail. Second, MDN warns explicitly against iterating arrays with for...in, because array elements are stored as standard object properties at heart, and for...in lists every enumerable property, including any extra property you happened to attach to the array. To walk an array, use for, for...of, or forEach — never for...in. The cafe's menu rendering is forEach: each item builds one card, the callback only renders and returns nothing, and the responsibilities stay cleanly split.
Step 7: map and filter — the two knives for building new arrays
map and filter are the two most used array methods, and both return a new array while the original stays untouched. map is a one-to-one transformation: run the callback on every item and collect the return values into a new array. MDN's example is: a1 is ["a", "b", "c"], and a1.map((item) => item.toUpperCase()) gives ["A", "B", "C"]. filter is "keep by condition": items whose callback returns true stay, the rest are dropped. MDN's example is: a1 is ["a", 10, "b", 20, "c", 30], and a1.filter((item) => typeof item === "number") gives [10, 20, 30].
flatMap is map followed by a flat of depth 1: in MDN's example a1 is ["a", "b", "c"], and flatMap((item) => [item.toUpperCase(), item.toLowerCase()]) gives ["A", "a", "B", "b", "C", "c"]. The menu page's working combination is: filter first to drop dishes containing an allergen, then map to show the remaining dish names in upper case. Remember the split of labor: use map to transform, filter to select — do not push into a new array by hand inside a forEach, which is rewriting with a loop what these two methods already do.
Step 8: find, findIndex, and their Last siblings — first match or last match
filter returns every matching item; find returns the first matching item itself. MDN's example is: a1 is ["a", 10, "b", 20, "c", 30], and a1.find((item) => typeof item === "number") gives 10 — the first number. findLast searches from the end, so on the same array findLast gives 30 — the last number. findIndex and findLastIndex return the index, not the element: findIndex gives 1, findLastIndex gives 5.
Which one to pick depends on what you want: the element itself, use find or findLast; the index, use findIndex or findLastIndex; every matching item, use filter; just whether one exists, use some, covered in the next section. When nothing matches, find returns undefined and findIndex returns -1, and the two must be told apart: undefined means "no element found", -1 means "no index found". The cafe's "find the first dish that is out of stock" is find: found, mark it red; not found, undefined, and the page simply shows "everything in stock", with no loop written at all.
Step 9: every, some, reduce — asking one question of a whole list
every and some are "ask a question" methods, returning true or false. every asks "does every item pass": in MDN's example isNumber tests whether a value is a number, [1, 2, 3].every(isNumber) is true, and [1, "2", 3].every(isNumber) is false, because "2" is a string. some asks "does at least one item pass": [1, "2", 3].some(isNumber) is true, and ["1", "2", "3"].some(isNumber) is false. On the menu page, "does every dish have a photo" is every, and "is any dish out of stock" is some — readable at a glance.
reduce "folds" a list down to a single value: MDN's example is [10, 20, 30].reduce((accumulator, currentValue) => accumulator + currentValue, 0), which gives 60. The initialValue rule must be learned by heart: with 0 given, the callback's first accumulator is 0 and its currentValue is the first element; without an initialValue, the callback's first two parameters are the first two elements of the array, and on every later call the first parameter is whatever the callback returned last time. MDN also warns that reduce and reduceRight are the least obvious of the iterative array methods, to be used only for algorithms that combine values to reduce a sequence down to a single value. The cafe's order total is reduce: add up the price of every dish, with the initial value written as 0 — forget it, and an empty order throws outright.
reduceRight is reduce's twin, only it starts from the last element and works backwards. MDN's own words are that reduceRight works like reduce, but starts with the last element. For addition, where order does not matter, either gives the same answer; for joining strings in order, the two give completely different results. The cafe's "dishes ordered most recently" list, shown newest first, is reduceRight's job: fold from the last order backwards, and the result comes out in reverse time order. Remember the test: if order does not matter, use reduce; if it has to run backwards, use reduceRight — do not write a reverse just to get the order flipped.
Step 10: flat and groupBy — flatten the nesting, group the same kind together
When arrays nest inside arrays, use flat to flatten them. MDN's example is: [1, 2, [3, 4]].flat() gives [1, 2, 3, 4], flattening one level by default; pass a depth to go deeper. To group, use Object.groupBy: MDN's inventory example has asparagus as a vegetable, bananas and cherries as fruit, goat and fish as meat, and Object.groupBy(inventory, ({ type }) => type) gives an object with vegetables, fruit, and meat as keys, each holding its matching array. Note MDN's warning: the returned object references the same elements as the original array, not deep copies — change something inside them and the original array changes too.
If the grouping key cannot be a string — for example the key is an object that might change — use Map.groupBy instead, which groups elements into a Map whose key can be any value. The cafe's menu grouping is groupBy: dishes split by type into mains, drinks, and desserts, and the page renders three sections straight from the group keys, without writing the same filter three times. Remember the split: flat to flatten, groupBy to group — do not write a loop that stuffs items into an object one by one.
Step 11: An empty slot is not undefined — sparse arrays love to deceive
Empty slots and undefined are not the same thing, and MDN spends a whole section on it. Empty slots are created five ways: Array(5) makes 5 empty slots outright; consecutive commas in a literal, [1, 2, , , 5]; writing to an index beyond the length; elongating the array by setting .length directly; and deleting an element with delete. In MDN's example arr is [1, 2, , , 5]: reading arr[2] gives undefined, a for...of loop prints 1, 2, undefined, undefined, 5, and spreading [...arr] gives [1, 2, undefined, undefined, 5] — in all these operations empty slots behave as if filled with undefined.
But iteration methods see it differently: on the same arr, map((i) => i + 1) gives [2, 3, empty, empty, 6], the slots stay empty; forEach only prints 1, 2, 5, skipping the slots entirely; filter(() => true) gives [1, 2, 5], the slots are dropped; some((k) => !k) returns false, because the empty slots never took part in the test; and Object.keys(arr) is only ["0", "1", "4"]. That is how the cafe's menu broke: a dish was removed with delete, an empty slot stayed in the array, and map rendering kept the slot, leaving a blank card on the page. Remember the test: remove elements with splice, never with delete; to clear, set length to 0, never delete one by one.
Step 12: What looks like an array is not always an array
Some objects look like arrays — they have a length and can be read by index — but are not arrays and have none of the array methods. MDN names two: the NodeList returned by document.getElementsByTagName(), and the arguments object available inside a function body. arguments provides a length attribute but does not implement array methods like forEach, so calling arguments.forEach throws a TypeError: arguments.forEach is not a function. MDN's way around it is an indirect call: Array.prototype.forEach.call(arguments, (item) => {...}), borrowing the method from the array prototype.
In modern code the more common fix is to convert to a real array first and then work with it, for example with Array.from or the spread operator — but the principle is the same: confirm it is a real array before calling array methods. The cafe's order page stepped into this trap: querySelectorAll returns a NodeList, calling map on it directly threw, and converting with Array.from first and then mapping fixed it. Remember the test: before calling a method, ask "is this a real array" — Array.isArray answers in one call, and if it is false, convert first, then call.
Step 13: 120 array incidents in one month — check yourself against the chart

The chart above shows a fictional month for the Greenstone Cafe project: 120 incidents related to arrays in total. Using a mutating method by mistake and changing the original array: 38, or 31.7%, the largest group; sort with no compare function, so numbers were ordered as strings: 27, or 22.5%; sparse-array empty slots skipped, leaving blank cards on the page: 22, or 18.3%; reduce with no initial value, so an empty order threw outright: 19, or 15.8%; calling forEach directly on an array-like object, throwing a TypeError: 14, or 11.7%. 38 + 27 + 22 + 19 + 14 = 120, and the books balance. These numbers are invented examples, meant to show at a glance that the first group is nearly a third — and that its root cause is only one thing: not knowing whether a method changes the original array.
Checklist: after writing code that processes an array, tick each item
First, build arrays with brackets by default, and use Array.of for a single number element — never Array(number). Second, indexes start at 0, length is always the highest index plus 1, and writing length can truncate or clear an array. Third, push and unshift return the length, pop and shift return the removed element — never take the return value for the new array. Fourth, concat, join, slice, and at leave the original alone, while splice, reverse, and sort change it in place — ask "does it change the original" before using one. Fifth, sorting numbers needs a compare function: negative, zero, and positive mean before, equal, and after. Sixth, forEach does things and returns nothing; map builds a new array, filter keeps by condition — do not push by hand inside forEach. Seventh, find or findLast for an element, findIndex or findLastIndex for an index; not found means undefined or -1. Eighth, every for "is it all", some for "is there at least one", reduce to fold into one value — and never forget the initial value. Ninth, flat to flatten, groupBy to group, and remember the grouped result still references the original elements, not deep copies. Tenth, remove elements with splice, never with delete; an empty slot is not undefined, and iteration methods skip it. Eleventh, confirm it is a real array before calling a method — convert an array-like object to a real array first. If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.
Comments (0)
Sources
Related articles
localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.
One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.