This post will discuss how to get the first element of an array in JavaScript.

1. Using [] operator

A simple and fairly efficient solution to fetch the first element of an array in JavaScript is using the [] operator. This method is demonstrated below:

Download  Run Code

2. Using Array.prototype.shift() function

The shift() method returns the first element from an array but removes it from the array as well. To avoid modifying the original array, you can create a copy of the array before calling the shift() method. You can do this in two ways:

⮚ Slicing

Download  Run Code

⮚ ES6 Spread operator

Download  Run Code

3. Using Destructuring Assignment

Alternatively, you can use the Destructuring Assignment syntax to get the first element of the array.

Download  Run Code

4. Using jQuery

With jQuery, you can pass index 0 to .get(index) to retrieve the first element.

Download Code

5. Using Underscore/Lodash Library

Alternatively, with the Underscore JavaScript library, you can use the _.first method, which simply returns the first element of an array if no arguments are specified. Its aliases _.head and _.take can also be used.

Download Code

 
Similarly, Lodash has the _.head method, which returns the first element of an array. Its alias _.first can also be used.

Download Code

That’s all about getting the first element of the array in JavaScript.