Last updated on Sep 24, 2020 by Suraj Sharma
In this tutorial, you will learn 3 different ways to get the first element of an array in JavaScript
JavaScript arrays are zero-indexed, that means the index of the first element is 0 and the last element is at index (array’s length - 1).
const array = ['India', 'United States', 'Brazil'];
const firstElement = array[0]; // 'India'
const lastElement = array[array.length-1]; // 'Brazil'
We can use the slice()
method to get the first element of a JavaScript array by passing 0
as a first parameter and 1
as a second parameter.
It returns a new array of length 1.
const array = ['India', 'United States', 'Brazil'];
const subArray = array.slice(0, 1); // ['India']
The Array destructuring assignment introduced in ES6 can help us get the first element of an array.
const array = ['India', 'United States', 'Brazil'];
const [firstElement] = array;
console.log(firstElement) // 'India';
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.