If you are a non-member, you can read this story through the link here.
In programming, arrays are one of the most important data structures.
In JavaScript, arrays are very powerful, and it is very important to have deep understanding of all related topics regarding array and his methods.
The idea of this article is to show a complete overview of the methods available to get the first element of the array.
1. Zero index
Definitely, the most common way is to use zero index for access to the first element. Immutable concept, so the array is not changed.
const animals = ['cat', 'dog', 'cow'];
const first = animals[0];
console.log(first);
// result: 'cat'
2. Destructuring assignment
Here, the idea is to use destructuring assignment for array matching.
Immutable concept, so the array is not changed.
const animals = ['cat', 'dog', 'cow'];
const [first] = animals;
console.log(first);
// result: 'cat'
3. ECMAScript 2022 feature — at method
Here, instead of zero index, you can use Array.prototype.at() method.
Immutable concept, so the array is not changed.
const animals = ['cat', 'dog', 'cow'];
const first = animals.at(0);
console.log(first);
// result: 'cat'
4. Shift method
Array.prototype.shift() method returns the first element of the array and changes the array length, so mutable concept — array is changed.
const animals = ['cat', 'dog', 'cow'];
const first = animals.shift();
console.log(first);
console.log(animals);
// result: 'cat', ['dog', 'cow']
5. Find method
Array.prototype.find() method can be used with filter predicate function to check if the index is zero. Immutable concept, so the array is not changed.
const animals = ['cat', 'dog', 'cow'];
const first = animals.find((_, index) => !index);
console.log(first);
// result: 'cat'
Conclusion
As you can see, there are a lot of variations when you need to get the first element of the array. If you don’t want to change the original array then zero index, destructuring assignment and ECMAScript 2022 feature are the best options. Otherwise, if you are ok with array change, you can use shift method.
After all, zero index and shift method are used the most.
Thanks for reading.
I hope you enjoyed the article and learned something.