How do I find the last element in an array with JavaScript?

Viewed 3046

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]);
    }
}
3 Answers

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

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]);
    }
}

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([]))

Related