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.

  • You are writing a new question on Stackoverflow just to ask "How do I know if an array is empty"? :| – Jeremy Thille Nov 24 '20 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. :-) – JSmart523 Nov 24 '20 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] } } – Yonas Tesh Oct 08 '21 at 15:04

1 Answers1

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;
Thejool
  • 514
  • 4
  • 9