'Javascript: Function returning last element of array

I'm taking Colt Steele's Udemy Course titled: "The Web Developer Bootcamp 2020". I have however become stuck on a certain coding exercise. The exercise objective is as follows: Please write a function called lastElement which accepts a single array argument. The function should return the last element of the array(without removing the element). If the array is empty, the function should return null.

I have tried coming up with a solution but cant seem to figure it out. My current best guess is this :

function lastElement (num) {
if (num !== undefined){
    return num[num.length -1];
} return null;

}

I'm interested in knowing why the function I have written doesn't work and some pointers on how I should rethink the function, so that it does work.

Best Regards Andreas



Solution 1:[1]

Change to this condition.

if (num && num.length>0) 

Solution 2:[2]

You can use this:

function lastElement(arr) {
if(arr.length>0){
   return arr[arr.length-1];
} else{
   return null;
}

Solution 3:[3]

change your condition to:

if(num && num.length>0)

additionally, if they decide to enter an argument that is not an array,

if(num && Array.isArray(num) && num.length>0)

Solution 4:[4]

The problem lies in the difference of truthy and falsy values: Empty array is truthy but undefined is falsy, so []!==undefined is true, but:

num[num.length -1]; 

means:

num[-1]; 

which is undefined .

Solution 5:[5]

function lastElement(test) {
if (test.length == 0)
    return null;
else
    return test[test.length - 1];
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sazid Ahmed Nassir
Solution 3 Ron
Solution 4 Saar Seri
Solution 5 Nikola Lukic