get last x elements of array javascript code example

Example 1: javascript get last element of array

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

Example 2: javascript slice array

// array.slice(start, end)
const FRUITS = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = FRUITS.slice(1, 3);
// citrus => [ 'Orange', 'Lemon' ]

// Negative values slice in the opposite direction
var fromTheEnd = FRUITS.slice(-3, -1);
// fromTheEnd => [ 'Lemon', 'Apple' ]

Example 3: get last element of array javascript

let colors = ["red", "yellow", "green"];
let lastELement = colors[colors.length - 1]