Get the first element of an array in JavaScript
Question:
How to get the first element of an array in JavaScript? Answer:
const firstItem = myArray.shift();
Description:
To get the first element of an array in JavaScript you can use the shift() method on your array. The shift() method removes the item from the original array.
For example if you have the following array:
let myArray = [1, 2, 3, 4, 5];
Then the following code gets the first item:
const firstItem = myArray.shift();
After that the values are:
// firstItem: 1
// myArray: [2, 3, 4, 5]
Reference:
JavaScript Array.shift() reference
Share "How to get the first element of an array in JavaScript?"
Related snippets:
- Check if an array contains a value
- Append an array to another in JavaScript
- Get the first element of an array in JavaScript
- Convert Map values to array in JavaScript
- Convert array to comma separated string using JavaScript
- Get the minimum value in an array using JavaScript
- Get the maximum value in an array using JavaScript
- Remove duplicates from array in JavaScript
- Split a string into words
- Use foreach in JavaScript
Tags:
get, first, array, element, item, javascript Technical term:
Get the first element of an array in JavaScript