DevNotes
@devnotes ·
JavaScript Part 6: Arrays
An array is an ordered list of values, like the items in a cart. You'll use arrays more than anything else in JavaScript.
Making one and reading it
Positions, called indexes, start at 0, not 1. That's why the last item is at length - 1. Asking for an index that doesn't exist, like fruits[10], gives undefined rather than an error.
Changing it
All of this works even though fruits is a const. const stops the name from pointing at a different array, but the array itself can still change.
Finding things
The big three: map, filter, find
These take a function and run it on every item. They replace most of the loops you'd otherwise write by hand.
mapmakes a new array with every item changed by your function. Same length, new values.filtermakes a new array holding only the items your function says yes to.findgives you the first item that matches, orundefinedif none do.
None of them touch the original. prices is still [100, 250, 40, 600].
To add everything up, reduce carries a running total along the array:
The 0 at the end is where the total starts.
Sorting has a trap
By default, sort compares items as text, so "100" comes before "5", the same way "apple" comes before "banana". For numbers, always pass the comparison. Also, unlike map and filter, sort changes the original array.
Chaining
map and filter both return arrays, so you can chain them:
You'll write a lot of code like this in React, turning data into what shows on the screen.
Try it
Start with const marks = [45, 82, 67, 91, 38, 74];. Use filter to keep the passing marks (40 and above), map to add 5 bonus marks to each, and reduce to add them up so you can work out the average.
Next: JavaScript Part 7: Objects
Join WIK to like and reply to DevNotes and see more like this.