Welcome to the next post in my Code Fix series! In this article, I'll be going over someone's code to get the last element in an array.
The Task
The person was tasked to make a function called lastElement which takes an array and returns the last element. The function should return null if the array is empty.
// Expected output
lastElement([3,5,7]) // 7
lastElement([1]) // 1
lastElement([]) // null
The Problem
The person tried the code below, which wasn't getting the expected results:
function lastElement(array) {
let a = [];
if (array !== a) {
return array[array.length - 1];
}
return null;
}
Why It Doesn't Work
The code above is comparing the input array to an empty array in the variable a.
function lastElement(array) {
let a = []; // empty array in the variable a
// comparing the input array to an empty one
if (array !== a) {
return array[array.length - 1];
}
return null;
}
This doesn't work because when comparing arrays like above, their references (or where they're stored) are compared - not their contents.
For example:
// Random sets of arrays
const nums = [1, 2, 3];
nums === [1, 2, 3]; // false
const anotherArray = [1, 2, 3];
anotherArray === nums; // false
const copyOfNums = nums;
copyOfNums === nums; // true
The Solution
For this example, it's better to check if the array is null by comparing its length:
function lastElement(inputArray) {
// an array is empty if its length is 0
if (inputArray.length === 0) {
return null;
}
return inputArray[inputArray.length - 1];
// 1 is subtracted from the total length of the array
// arrays are indexed starting at 0
}
If you wanted to shorten this, you can rewrite the if-statement as such:
function lastElement(inputArray) {
if (!inputArray.length) {
return null;
}
return inputArray[inputArray.length - 1];
}
This also checks if there is no length on inputArray. Same comparison, just less code to type!
Finally, if you wanted to write this as an arrow function:
const lastElement = inputArray => {
if (!inputArray.length) {
return null;
}
return inputArray[inputArray.length - 1];
}
I hope this helped! Stay tuned for more, cheers!