Get first element of array in JavaScript
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:
|
1 2 3 4 5 6 7 |
var arr = [ 1, 2, 3, 4, 5 ]; var first = arr[0]; console.log(first); /* Output: 1 */ |
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
|
1 2 3 4 5 6 7 8 |
var arr = [ 1, 2, 3, 4, 5 ]; var first = arr.slice(0, 1).shift(); console.log(first); /* Output: 1 */ |
⮚ ES6 Spread operator
|
1 2 3 4 5 6 7 8 |
var arr = [ 1, 2, 3, 4, 5 ]; var first = [...arr].shift(); // costly for large arrays console.log(first); /* Output: 1 */ |
3. Using Destructuring Assignment
Alternatively, you can use the Destructuring Assignment syntax to get the first element of the array.
|
1 2 3 4 5 6 7 8 |
var arr = [ 1, 2, 3, 4, 5 ]; const [first] = arr; console.log(first); /* Output: 1 */ |
4. Using jQuery
With jQuery, you can pass index 0 to .get(index) to retrieve the first element.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); var arr = [ 1, 2, 3, 4, 5 ]; var first = $(arr).get(0); console.log(first); /* Output: 1 */ |
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.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore'); var arr = [ 1, 2, 3, 4, 5 ]; var first = _.first(arr); console.log(first); /* Output: 1 */ |
Similarly, Lodash has the _.head method, which returns the first element of an array. Its alias _.first can also be used.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('lodash'); var arr = [ 1, 2, 3, 4, 5 ]; var first = _.head(arr); console.log(first); /* Output: 1 */ |
That’s all about getting the first element of the array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)