Getting the last element from an array
Getting the last element in an array by doing math with its length can lead to off-by-one errors. Doing this with Array.prototype.pop()
would remove the value from the array. We can write a function that leaves the value in the array and does the math with length for us.
const last = array => array[array.length - 1]
last(['Bibidi', 'Babidi', 'Boo']) // ⇒ 'Boo'
last([59, 75, 78, 752, 789, 881]) // ⇒ 881
More fire tips
Checking if something is an array
We cannot use the typeof operator in JavaScript to check if something is an array or not. Luckily, there is a helper function on the Array prototype for that.
Read fire tipMapping array values with constructors
Syntactic sugar on the Array prototype’s map function and type constructors being functions allow us to quickly map values from one type to another.
Read fire tip