0

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

0

5 Answers 5

2

You can use this:

function lastElement(arr) {
if(arr.length>0){
   return arr[arr.length-1];
} else{
   return null;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Change to this condition.

if (num && num.length>0) 

1 Comment

if(num) checks for all 'falsy' values. Check whether 'num' exists.
1
function lastElement(test) {
if (test.length == 0)
    return null;
else
    return test[test.length - 1];
}

Comments

0

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)

Comments

0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.