How to get the last item in an array in JavaScript

4 Answers

0 votes
let arr = [1, 2, 3, 4, 5, 6, 7];
 
let lastitem = arr[arr.length - 1];
 
console.log(lastitem);
console.log(arr);

 
 
   
     
/*
run:
     
7
[1, 2, 3, 4, 5, 6, 7]
     
*/

 



answered Jan 31, 2021 by avibootz
edited Jan 31, 2021 by avibootz
0 votes
let arr = [1, 2, 3, 4, 5, 6, 7];
 
let lastitem = arr.slice(-1)[0];
 
console.log(lastitem);
console.log(arr);

 
 
   
     
/*
run:
     
7
[1, 2, 3, 4, 5, 6, 7]
     
*/

 



answered Jan 31, 2021 by avibootz
0 votes
let arr = [1, 2, 3, 4, 5, 6, 7];

let lastitem = arr.slice(-1).pop();

console.log(lastitem);
console.log(arr);

 
 
   
     
/*
run:
     
7
[1, 2, 3, 4, 5, 6, 7]
     
*/

 



answered Jan 31, 2021 by avibootz
0 votes
let arr = [1, 2, 3, 4, 5, 6, 7];
 
let lastitem = arr.pop();
 
console.log(lastitem);
console.log(arr);

 
 
   
     
/*
run:
     
7
[1, 2, 3, 4, 5, 6]
     
*/

 



answered Jan 31, 2021 by avibootz
...