xxxxxxxxxx
var colors = ["red","blue","green"];
var green = colors[colors.length - 1];//get last item in the array
xxxxxxxxxx
var foods = ["kiwi","apple","banana"];
var banana = foods[foods.length - 1]; // Getting last element
xxxxxxxxxx
const array = ["foo", "bar", "fizz", "buzz"];
const lastElem = array.at(-1); // returns "buzz"
xxxxxxxxxx
let array = [1,2,3,4,5]
let sliced = array.slice(-1)[0]
//OR
let popped = array.slice(-1).pop()
//OR
let lengthed = array[array.length - 1]
xxxxxxxxxx
var Cars = ["Volvo", "Mazda", "Lamborghini", "Maserati"];
//We can get the total number of elements like this.
var hmCars = Cars.pop();
//hmCars is now Maserati
console.log(hmCars)
xxxxxxxxxx
const arr = [5, 3, 2, 7, 8];
const last = arr.at(-1);
console.log(last);
/*
Output: 8
*/
//Better and shorter way will be
const arr = [1,2,3,4]
console.log(arr.pop())
/*
Output: 4
*/
xxxxxxxxxx
const arr = [1,2,3,4,5]
const last = arr.pop()
// last: 5
// arr: [1,2,3,4]
// Note this does modify the array