1var colors = ["red","blue","green"];
2var green = colors[colors.length - 1];//get last item in the array
1// Method - 1 ([] operator)
2const arr = [5, 3, 2, 7, 8];
3const last = arr[arr.length - 1];
4console.log(last);
5/*
6 Output: 8
7*/
8
9// Method - 2 (Destructuring Assignment)
10const arr = [5, 3, 2, 7, 8];
11
12const [last] = arr.slice(-1);
13console.log(last);
14/*
15 Output: 8
16*/
17
18// Method - 3 (Array.prototype.pop())
19const arr = [5, 3, 2, 7, 8];
20
21const last = arr.slice(-1).pop();
22console.log(last);
23/*
24 Output: 8
25*/
26
27// Method - 4 (Underscore/Lodash Library)
28const _ = require("underscore");
29
30const arr = [5, 3, 2, 7, 8];
31const last = _.last(arr);
32console.log(last);
33/*
34 Output: 8
35*/
1var colors = ["red","blue","green"];
2var green = colors[colors.length - 1]; //get last item in the array
1let array = [1,2,3,4,5];
2let lastElement = array.pop();
3
4// array -> [1,2,3,4];
5// lastElement = 5;