1 of 25

Arrays

1.1.1

2 of 25

Basic

MECHANICS

1

3 of 25

You know a lot already!

  • Arrays are a lot like strings
  • They are 0 indexed and have a `.length`
  • Access values with bracket notation `[ ]`
  • Iterate through them with a loop with the `.length` property

4 of 25

strings are just arrays of characters, so the overlap makes sense

5 of 25

Arrays are “mutable”

  • Unlike strings, arrays are mutable
    • Alter values at index
    • Delete entire contents
    • Insert/remove values (more later)

mutation !== reassignment

`const` doesn’t block mutations!

6 of 25

Destructuring is a really cool trick that’s used all the time

7 of 25

Advanced

MECHANICS

2

8 of 25

Advanced

  • You can also “destructure” arrays into variables
  • Arrays can contain other arrays
    • Access with back-to-back brackets `[ ][ ]`
  • We have a new type of `for` loop!
    • `for of` loops are more concise
    • They are less dynamic though

9 of 25

Destructuring is a really cool trick that’s used all the time

10 of 25

nested data structures are common, but let’s start simple

11 of 25

for of loops are less flexible, but more compact

12 of 25

Copy vs

MUTATE

3

13 of 25

Making copies

  • Make a shallow copy to avoid mutations
  • We still have `.slice()` method
  • We also have the “spread operator” `…`
    • Whole copy, use `...`
    • Copy section, use `.slice()`

14 of 25

The spread operator is a new but useful tool to JS

15 of 25

Changing === mutating

  • Sometimes you do want to modify or “mutate”
  • We have a lot of methods!
  • Add/remove to end: `.push()`, `.pop()`
  • Add remove to start: `.unshift()`, `.shift()`
  • Add/remove to middle: `.splice()`
    • That’s splice not slice

16 of 25

push, pop, unshift, and shift affect the front and back

17 of 25

18 of 25

splice() is how we interact with the middle of arrays

19 of 25

Mutations vs Copy

  • We’ve talked about “pure” functions
    • same input means same output
    • No side effects

mutating an argument is a side effect

  • In general: copying is safer, but mutations are sometimes needed

20 of 25

21 of 25

Pass By

REFERENCE

4

22 of 25

Arrays pass references

  • Why copy methods? Why not `arr1 = arr2`?
  • Array assignments are “references” to spaces in memory, not the value itself
  • primitives “pass by value”
  • arrays/objects “pass by reference”

Accidentally mutating references is a common bug

23 of 25

24 of 25

25 of 25

A more complex example