javascript get array last index code example

Example 1: javascript get last element of array

var foods = ["kiwi","apple","banana"];
var banana = foods[foods.length - 1]; // Getting last element

Example 2: Javascript get last item in array

var colors = ["red","blue","green"];
var green = colors[colors.length - 1]; //get last item in the array

Example 3: js last index of

const str = "Users/Edit/12345";
let idx = str.lastIndexOf("/"); // returns 10
idx = str.lastIndexOf("x"); // returns -1

idx = str.lastIndexOf("Edit") // returns 6
idx = str.lastIndexOf("edit") // returns -1 -- case sensitive

// add "from" parameter
// the search happens backwards, starting at the provided from parameter
idx = str.lastIndexOf("s"); // returns 4
idx = str.lastIndexOf("s", 3); // returns 1

Example 4: javascript get last element of array

console.log(2)