3

I'm trying to return the last element in an array or, if the array is empty it should return null. What am I doing wrong / what is the best way to do this?

Here's my code:

function lastElement(x, y, z) {
    if (lastElement.length < 1 || lastElement === undefined) {
         return null; 
    }
    else {
        return(lastElement[lastElement.length - 1]);
    }
}
  • 1
    Would `return lastElement.slice(-1)` suffice? --- Also why are you referencing `lastElement`? That's the function name. `x`, `y`, and `z` are never used. – evolutionxbox Oct 20 '20 at 12:16
  • looks like a duplicate of https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array – AnthumChris Oct 20 '20 at 12:17
  • Does this answer your question? [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Md Sabbir Alam Oct 20 '20 at 12:18

3 Answers3

3

You need to use a local variable which has a different name as the function, preferably a paramter and check if an array is handed over which has a length.

Then return the last item or null;

function getLastElement(array) {
    return Array.isArray(array) && array.length
        ? array[array.length - 1]
        : null;
}

console.log(getLastElement());       // null
console.log(getLastElement([]));     // null
console.log(getLastElement([1]));    // 1
console.log(getLastElement([1, 2])); // 2
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
1

lastElement is the name of your function.

You need to use array for this, Maybe this way:

function lastElement(array) {
    if (array.length < 1 || array === undefined) {
         return null; 
    }
    else {
        return(array[array.length - 1]);
    }
}
Eylon Shmilovich
  • 126
  • 1
  • 1
  • 8
0

You do not need a function for this you can just use the .length property. Also if you don't care if its undefined (when the array is empty) you can remove the. || null

let some_array = [1,2,3,4]
let last_element = some_array[some_array.length-1] || null
console.log(last_element)

If you where do really need this in a function

let some_array = [1,2,3,4] 
function get_last(array){
  //if the array is empty return null
  return array[array.length-1] || null 
}
console.log(get_last(some_array))
console.log(get_last([]))
tovernaar123
  • 178
  • 11