๐Ÿ˜œ

์ญˆ๋‚˜์•„๋น  ๋ธ”๋กœ๊ทธ

JUNA
STUDIO

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

๋ฐœํ–‰์ผ: Feb, 2025
์กฐํšŒ์ˆ˜: 20
๋‹จ์–ด์ˆ˜: 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.


Tags: #JavaScript#Array Methods#Performance Comparison#Access Last Element#Slice Method#Pop Method

JavaScript/TypeScript > ์ด ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ํฌ์ŠคํŒ…

JUNA BLOG VISITORS
Today
7
 (
updown
-7
)
Total
657
 (
updown
+7
)

ยฉ 2025 juniyunapapa@gmail.com.