xxxxxxxxxx
var colors = ["red","blue","green"];
var green = colors[colors.length - 1]; //get last item in the array
xxxxxxxxxx
const array = ["foo", "bar", "fizz", "buzz"];
const lastElem = array.at(-1); // returns "buzz"
xxxxxxxxxx
const arr = [2, 4, 6, 8, 10, 12, 14, 16];
const lastElement1 = arr[arr.length - 1]; // Method 1
const lastElement2 = arr.slice(-1); //Method 2
const lastElement3 = arr.pop(); //Method 3
const lastElement4 = arr.at(-1) //Method 4 Best Approach
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
var colors = ["red","blue","green"];
var green = colors[colors.length - 1];//get last item in the array
const array = ["foo", "bar", "fizz", "buzz"];
const lastElem = array.at(-1); // returns "buzz"
arr.slice(-1)[0]
xxxxxxxxxx
if (loc_array[loc_array.length - 1] === 'index.html') {
// do Mohammed alraey
} else {
// something else
}