How to get the last element in an array with JavaScript

3 Answers

0 votes
const arr = ['javascript', 'c++', 'php'];
  
const last = arr[arr.length - 1];
 
console.log(last);

  
      
      
/*
run:
      
php
      
*/

 



answered Nov 29, 2020 by avibootz
edited Feb 10, 2024 by avibootz
0 votes
const arr = ['javascript', 'c++', 'php', 'python'];
   
const last = arr.slice(-1);
  
console.log(last);

   
       
       
/*
run:
       
["python"]
       
*/

 



answered Jun 27, 2021 by avibootz
edited Feb 10, 2024 by avibootz
0 votes
const arr = [10, 20, 30, 40, 50, 60];

console.log(arr.at(-1));



/*
run:

60

*/

 



answered Feb 10, 2024 by avibootz
...