Create Exercise Array
const exercises = ['pull-up', 'push-up', 'squat', 'deadlift']
If we want to grab the first one in our list, we use
exercises, to grab second use
exercises but what if we don’t know the total exercise number in our list?
No problem, there are a few ways we can do that.
1. Find last element with array.length
array.length property. To use it we need to first set up a variable, and then assign our array to it:
const lastExercise = exercises[exercises.length - 1]
Now if you run
console.log(lastExercise) your console will output the last element of the array, in his case
2. Find last element using pop()
pop() which also gets the last element of an array but in a different way. Try it out:
The pop() method indeed targets the last element in our array, but beware it not only finds the last element of your array, but it also removes it.
console.log(exercises) right below
exercises.pop() you’ll see that your array now has 3 elements instead of the original 4. This may or may not be what you want, depending on your use case.
3. Find last element with the Array slice() Method
The last method I want to show you is similar to the
length method, but here we use
slice() instead, like this:
const lastExercise = exercises.slice(-1)
Now if you
console.log(lastExercise) you’ll get the same result as in the
length example. A lot of developers find the
slice method to be more reader-friendly than the
length method, but unfortunately its also much slower, performance-wise.
To see what I mean, try running this slice vs. length comparison test on jsperf.com
So should you use the most performant or the most readable array method? There’s no right or wrong answer, it depends on your context.
In general, I tend to gravitate towards choosing performance over convenience as a rule of thumb, e.g. when working with images. It’s not a black and white question though. In terms of finding the last element in a simple array, you won’t even notice a performance difference between
length in your app, unless you’re executing millions of functions per second.
Always make decisions based on context.