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

Here are the ways to get the first and last element in an array in JavaScript:

  1. Using length property
  2. Using Array.pop() and Array.shift()
  3. Using Array.slice()
  4. Using Array.filter()
  5. Using Spread Operator

Method 1: Using the “length” property

We can use the concept of indexing to get the first and last elements of Array.

JavaScript indexes are zero-based.

We can simply access the first and the last elements of an Array by specifying 0, and the last index can be accessed through length-1.

function elements(a) {
  console.log(`The first element of the array is: ${a[0]}`);
  console.log(`The last element of the array is: ${a[a.length - 1]}`);
}

let nm = [23, 34, 233, 3, 5];
elements(nm);

Output

The first element of the array is: 23

The last element of the array is: 5

Method 2: Using pop() and shift() Method

There are indirect ways to find the array’s first and last elements.

Array.pop() method removes the last element from the array and returns it, and Array.shift() method removes and returns the first element from an array.

function elements(a) {
   let first = a.shift(0);
   let last = a.pop();
   console.log(`The last element of the array is: ${first}`);
   console.log(`The last element of the array is: ${last}`);
}

let nm = ["john", "william", "fredrik", "collins", "patrik"];

elements(nm);

Output

The last element of the array is: john

The last element of the array is: patrik

Method 3: Using Array.at() Method

To get the first and last element of an array, you can also use Array.at() method. This method takes an integer value and returns the item at that index. If the index is out of range, it returns -1.

function elements(a) {
  console.log(`The first element of the array is: ${a.at(0)}`); 
  console.log(`The last element of the array is: ${a.at(-1)}`);
}
let nm = [23, 34, 233, 3, 5];

elements(nm);

Output

The first element of the array is: 23

The last element of the array is: 5

Method 4: Using Array.filter() Method

The Array.filter() method creates a new array with all elements that pass the test implemented by the provided function.

Using the filter() method, you can check the current element’s index against 0 (the first element) and array.length – 1 (the last element).

let arr = [1, 2, 3, 4, 5];

let firstAndLast = arr.filter((value, index, array) => {
  return index === 0 || index === array.length - 1;
});

console.log(firstAndLast);

Output

[ 1, 5 ]

Method 5: Using Spread Operator

The spread operator (…) can be used with array destructuring to extract the first and last elements of the array.

let arr = [1, 2, 3, 4, 5];

let [first, ...rest] = arr;
let last = rest.length ? rest[rest.length - 1] : first;

console.log(first, last);

Output

1 5