How to Get the First Element of a JavaScript Array?

You can get the first element of a JavaScript array in the following ways:

Get the First Element Without Modifying the Original Array

Using either of the following approaches does not mutate the original array when trying to get the first element:

Directly Accessing First Element by Index:

You can simply, directly access the first element of an array by index 0, for example, like so:

const arr = [1, 2, 3, 4];
const firstElem = arr[0];

console.log(firstElem); // output: 1
console.log(arr); // output: [1, 2, 3, 4]

When you try to get the first index of an empty array, you will get undefined:

const arr = [];
const firstElem = arr[0];

console.log(firstElem); // output: undefined

Using Destructuring to Get First Array Element:

In ES6+, you can also use destructuring to get the first element of an array. For example:

// ES6+
const arr = [1, 2, 3, 4];
const [firstElem] = arr;

console.log(firstElem); // output: 1
console.log(arr); // output: [1, 2, 3, 4]

When using array destructuring to get the first element of an empty array, you will get undefined:

// ES6+
const arr = [];
const [firstElem] = arr;

console.log(firstElem); // output: undefined

Get the First Element and Remove it From the Original Array

If you wish to get the first element, as well as remove it from the original array, then you can simply use the Array.prototype.shift() method, for example, like so:

const arr = [ 1, 2, 3, 4 ];
const firstElem = arr.shift();

console.log(firstElem); // output: 1
console.log(arr); // output: [2, 3, 4]

Using the Array.prototype.shift() method on an empty array would return undefined. For example:

const arr = [];
const firstElem = arr.shift();

console.log(firstElem); // output: undefined

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.