[JavaScript] Three ways to get the last element of an array

발행일: Feb, 2025
조회수: 0
단어수: 115

JavaScript Array Methods for Accessing the Last Element

Table of Contents

1. Access Last Element Using Array Length

Retrieve the last element by specifying the index using the array length.


const arr = [1, 2, 3, 4, 5];

// last element by length
console.log(arr[arr.length - 1]);

2. Retrieve Last Element Using Slice Method

Use the slice method to get the last element.


const arr = [1, 2, 3, 4, 5];

// last element by slice
console.log(...arr.slice(-1));

3. Retrieve Last Element Using Pop Method

The pop method removes and returns the last element of an array.


const arr = [1, 2, 3, 4, 5];

// last element by pop
console.log(arr.pop());

4. Performance Comparison (Chrome)

Comparing the performance of the three methods.


const arr = [1, 2, 3, 4, 5];

// last element by length
console.time('lastindex');
console.log(arr[arr.length - 1]);
console.timeEnd('lastindex');

// last element by slice
console.time('slice');
console.log(...arr.slice(-1));
console.timeEnd('slice');

// last element by pop
console.time('pop');
console.log(arr.pop());
console.timeEnd('pop');

Result: The pop() method performs the fastest.

Although using arr.length - 1 is common, the performance difference suggests that using pop() is the better choice.


태그#JavaScript#Array Methods#Performance Comparison#Access Last Element#Slice Method#Pop Method

JUNA BLOG VISITORS

오늘0
Total0