SamanthaJ_V
SamanthaJ_V

Reputation: 59

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

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

Upvotes: 5

Views: 7798

Answers (5)

MD Golam Rakib
MD Golam Rakib

Reputation: 144

No need for any custom function. You can use any of the following process.

let arrItems = ['a', 'b', 'c', 'd'];

console.log('using array length');
let lastItem = arrItems[arrItems.length - 1];
console.log(lastItem);

console.log('using slice method');
let lastItem1 = arrItems.slice(-1)[0];
console.log(lastItem1);

console.log('using pop method');
let lastItem2 = arrItems.pop();
console.log(lastItem2);

//Output:

// using array length
// d
// using slice method
// d
// using pop method
// d

Upvotes: 0

trincot
trincot

Reputation: 350272

With the at method, the optional chaining and nullish coalescing operators, you can do:

const lastElement = array => array?.at?.(-1) ?? null;

// demo
console.log(lastElement([1,2,3])); // 3
console.log(lastElement([])); // null
console.log(lastElement(42)); // null
console.log(lastElement()); // null

Upvotes: 2

tovernaar123
tovernaar123

Reputation: 352

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

Upvotes: 0

Eylon Shmilovich
Eylon Shmilovich

Reputation: 719

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386604

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

Upvotes: 4

Related Questions