Hi Friends đź‘‹,
Welcome To Infinitbility! ❤️
Today, we are going to learn how to get the first 5 elements of an array in javascript, here we will use the javascript built-in method .slice()
which helps us to get our desired elements from an array.
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
– MDN
Okay, here we will do
- Create a sample array
- Use
.slice()
method to get first five elements - Check whether array elements get extracted properly or not
// create sample array variable
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant', 'lion', 'tiger'];
// Use `.slice()` method to get first five elements
const firstFiveAnimal = animals.slice(0, 4)
// Check array elements get extract properly or not
console.log("firstFiveAnimal", firstFiveAnimal)
When you run the above code, you will get only the first five elements,
Let’s check the output.
Output
![javascript, get first 5 elements of array](./images/output.jpg)
All the best đź‘Ť.