There are different approaches to accessing the first and last elements of an array in JavaScript.
1. Using Array Indexing
The basic method to access the first and last elements of an array is through indexing.
let arr = [10, 20, 30, 40, 50];
let first = arr[0];
let last = arr[arr.length - 1];
console.log(`First: ${first}, Last: ${last}`);
// Output: First: 10, Last: 50
2. Using shift() and pop() Methods
JavaScript provides shift()
to remove and return the first element and pop()
to remove and return the last element. While these methods modify the original array, they can also be used to extract the required elements.
let arr = [10, 20, 30, 40, 50];
let first = arr.shift();
let last = arr.pop();
console.log(`First: ${first}, Last: ${last}`);
// Output: First: 10, Last: 50
3. Using the slice() Method
The slice()
method allows you to create shallow copies of array elements without modifying the original array. You can use it to get the first and last elements.
let arr = [10, 20, 30, 40, 50];
let first = arr.slice(0, 1)[0];
let last = arr.slice(-1)[0];
console.log(`First: ${first}, Last: ${last}`);
// Output: First: 10, Last: 50
4. Using Destructuring Assignment
Array destructuring provides a clean and concise way to extract the first and last elements.
For the First Element
let arr = [10, 20, 30, 40, 50];
let [first] = arr;
console.log(`First: ${first}`);
// Output: First: 10
For Both Elements
Using the length
property to calculate the last element index:
let arr = [10, 20, 30, 40, 50];
let [first] = arr;
let last = arr[arr.length - 1];
console.log(`First: ${first}, Last: ${last}`);
// Output: First: 10, Last: 50
5. Using the at() Method (Introduced in ES2022)
The at()
method allows for retrieving elements using positive or negative indices. Negative indices are especially useful for getting the last element.
let arr = [10, 20, 30, 40, 50];
let first = arr.at(0);
let last = arr.at(-1);
console.log(`First: ${first}, Last: ${last}`);
// Output: First: 10, Last: 50
6. Using Loops
You can use loops to retrieve the first and last elements programmatically, especially when the array size or conditions are dynamic.
For First Element
let arr = [10, 20, 30, 40, 50];
let first;
for (let i = 0; i < arr.length; i++) {
first = arr[i];
break; // Exit after the first iteration
}
console.log(`First: ${first}`);
// Output: First: 10
For Last Element
let arr = [10, 20, 30, 40, 50];
let last;
for (let i = arr.length - 1; i >= 0; i--) {
last = arr[i];
break; // Exit after the first iteration
}
console.log(`Last: ${last}`);
// Output: Last: 50