0

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.

  1. lastElement([3,5,7]) //7
  2. lastElement([1]) //1
  3. lastElement([]) //null
** the code that I wrote **

let array = [3, 5, 7];

function lastElement (array) { 
    return array[array.length - 1];
}

I'm flummoxed on the last part with the function returning null if the array if empty.

3
  • You are writing a new question on Stackoverflow just to ask "How do I know if an array is empty"? :| Commented Nov 24, 2020 at 15:19
  • 1
    Don't let downvotes grind you down. Either you didn't know (in which case you're in the right place) or you had a mental block, in which case you're in the right place. :-) Commented Nov 24, 2020 at 15:32
  • If you want the easiest for beginners : function lastElement(array){ if(array.length === 0){ return null } else { return array[array.length - 1] } } Commented Oct 8, 2021 at 15:04

1 Answer 1

3

You can update your code a tiny bit to check if the array is empty and then return null like this:

return array.length ? array[array.length - 1] : null;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.