Introduction
In this lab, we will explore a JavaScript function that helps us find the last element of an array. We will learn how to check if an array is valid and has a length property, and how to use the length property to compute the index of the last element. We will also learn how to return undefined if the array is empty or invalid.
How to Get the Last Element of an Array in JavaScript
To get started with coding, open the Terminal/SSH and type node. The following function returns the last element in an array:
const last = (arr) => (arr && arr.length ? arr[arr.length - 1] : undefined);
To use it, you need to provide an array as an argument. The function checks if the array is truthy and has a length property. If both conditions are true, it computes the index of the last element of the array and returns it. Otherwise, it returns undefined.
Here are some examples:
last([1, 2, 3]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined
Summary
Congratulations! You have completed the Last Array Element lab. You can practice more labs in LabEx to improve your skills.