How to useArray.at() Method in Javascript
The Array.at() method in JavaScript allows to access elements of an array by their index. To get the first and last elements of an array using the at() method, pass the desired indices to the method. The first element has an index of 0. Array last element can be accessed by using the array’s length-1 as the index.
Example: In this example, we are using array.at() method.
// Get the array first and last elements using Array.at() method
function gfg() {
let s = ["Geeks", "for", "geeks", "computer", "science"];
// Get the first element (index 0)
console.log(s.at(0))
// Get the last element (index: length - 1)
console.log(s.at(s.length - 1))
}
// Call the function
gfg();
Output
Geeks science
Get the first and last item in an array using JavaScript
JavaScript array is used to store multiple elements in a single variable. It is often used when we want to store a list of elements and access them by a single variable. We will learn how to get the first & last element in an array in JavaScript, along with understanding their implementation through the examples.
These are the following approaches:
Table of Content
- Approach 1: Using length property in JavaScript
- Approach 2: Using Array.pop() and Array.shift() Method
- Approach 3: Using Array.slice() Method
- Approach 4: Using Array.filter() Method
- Approach 5: Using Spread Operator
- Approach 6: Using Array.at() Method
- Approach 7: Using Array.find() Method