Chapter 6 of 34
~13 minArrays & Array Methods
Arrays store ordered collections of values, and JavaScript gives them a rich set of built-in methods for reading, transforming, and reshaping that data - map, filter, and reduce are among the most important tools you will use daily.
Creating and Indexing Arrays
Arrays are created with square brackets: `const fruits = ['apple', 'banana', 'cherry']`. Elements are accessed by a zero-based index, so `fruits[0]` is `'apple'`. The `length` property tells you how many elements it holds.
Try it yourself
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Mutating vs Non-Mutating Methods
Some array methods change the original array in place - `push`/`pop` add/remove from the end, `unshift`/`shift` from the start, and `splice` can insert or remove anywhere. Others return a brand new array and leave the original untouched - `map`, `filter`, and `slice` are the common ones.
Knowing which category a method falls into matters a lot in frameworks like React, where mutating state directly can cause bugs - you generally want the non-mutating versions there.
Try it yourself
push/splice mutate, slice does not<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
map, filter, and reduce
`map` transforms every element and returns a new array of the same length. `filter` returns a new array containing only elements that pass a test. `reduce` boils an array down to a single accumulated value, and is the most flexible - map and filter can both be written in terms of it.
Try it yourself
Transforming a list of numbers<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Array Destructuring
Destructuring lets you unpack array elements into named variables in one line: `const [first, second] = fruits`. You can skip elements with commas, and use `...rest` to gather the remainder into a new array.
Try it yourself
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Coding challenge
Given the array [5, 12, 8, 3, 20, 15], use filter to keep only numbers greater than 10, then use map to double each remaining number, and log the final array to the output.
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. Which of these array methods mutates the original array?
2. What does `array.map()` return?
3. Which method would you use to boil an array down to a single total?
4. What does `const [a, , c] = [1, 2, 3]` do?