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

The array is one of the most widely used objects in almost any programming language. Programmers need to add a large chunk of data that are very similar to each other. For example marks of all the students in the class. Instead of creating too many variables for all the students in the class, it is much more convenient to create an array that can store all the marks in one go.

Get the First and Last Elements of an Array in JavaScript

We can use the concept of indexing in JavaScript to get the first and last elements of Array JavaScript. JavaScript indexes are zero-based. We can simply access the first and the last elements of an Array in JavaScript by specifying 0 and the last index can be accessed through length-1.

Example

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

Explanation

The above code can be explained as follows:

  1. First, we have created a user-defined function called elements. It takes one argument namely a.
  2. This will use the conole.log() function to print the first and the last elements of an Array in JavaScript using the indexing technique.
  3. We have used 0 as the index for the first element as per the rule and length-1 as the index for the last element.

Using pop() and shift() Method

There are some indirect ways to find the first and the last elements of the array too. Array.pop()  method removes the last item from the array and return it and Array. shift() method removes the first item from an array and return it.

Example

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

Using Array.at() Method

To get 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.

Example

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

Conclusion

In this article, we have learned about How to Get the First and Last Elements of an Array in JavaScript. Readers are however encouraged to think of many other logics to access the first and the last elements of an array.

Leave a Comment