OneBite.Dev - Coding blog in a bite size

get the last element of array in Javascript

Code snippet on how to get the last element of array in Javascript

  let arr = [1,2,3,4,5];
  let lastElement = arr[arr.length - 1];

This code first creates an array of numbers called arr with five elements. Then, the lastElement variable is set to the value of the last element of the array. This is done by accessing the last index of the array (in this case, the array is 5 elements long meaning the last index is 4) using arr.length - 1. The lastElement variable will now hold the value of the last element, in this case it would be 5.

javascript