How to Get the First and Last Elements of an Array in JavaScript

In this post you will learn how to get the First and Last Elements of an Array in JavaScript;

In Javascrpt to get the first and last elements of an array, access the array at index 0 and the last index.

const arr = [1, 2, 3, 4];

const first = arr[0];
console.log(first); //1

const last = arr[arr.length - 1];
console.log(last); //4

Indexes are zero-based in JavaScript. This means that the first element in the array has an index of 0 and the last element in the array has an index of arr.length – 1.

Note: When trying to access an array element at an index that does not exist does not throw an error, instead it returns undefined.

const arr = [];

const first = arr[0];
console.log(first); // undefined

const last = arr[arr.length - 1];
console.log(last); // undefined