Suggest an editImprove this articleRefine the answer for “How to get the last element of an array?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)The most universal way to get the last element of an array is via the index **`length - 1`**: `fruits[fruits.length - 1]`. **Key point:** for cross-browser compatibility use `arr[arr.length - 1]`, while for modern code `arr.at(-1)` looks much cleaner.Shown above the full answer for quick recall.Answer (EN)Image## 1. Via the index `length - 1` (the classic way) This is the most universal way, and it works everywhere ```javascript const fruits = ["apple", "banana", "cherry"]; const last = fruits[fruits.length - 1]; console.log(last); // "cherry" ``` - `length` is the array's length. - Since indexing starts at `0`, the last element sits at index `length - 1`. --- ## 2. Via the `.at(-1)` method (modern, ES2022+) A nicer and more readable way ```javascript const fruits = ["apple", "banana", "cherry"]; console.log(fruits.at(-1)); // "cherry" ``` Advantages: - You can use **negative indexes**, like in Python. - Works with both arrays and strings: ```javascript "hello".at(-1); // "o" ``` Supported in **Node.js 16+** and **modern browsers**. --- ## 3. Using `.slice(-1)` ```javascript const fruits = ["apple", "banana", "cherry"]; console.log(fruits.slice(-1)); // ["cherry"] console.log(fruits.slice(-1)[0]); // "cherry" ``` - `slice(-1)` returns a **new array** with the last element. - To get the element itself, you need `[0]`. --- ## 4. Using destructuring (ES6+) If you need to pull out the last element elegantly ```javascript const fruits = ["apple", "banana", "cherry"]; const [last] = fruits.slice(-1); console.log(last); // "cherry" ``` --- ## In short: | Method | Code | Returns | Note | |---|---|---|---| | Index | `arr[arr.length - 1]` | element | works everywhere | | `.at(-1)` | `arr.at(-1)` | element | modern | | `.slice(-1)[0]` | | element | creates a new array | | Destructuring | `const [last] = arr.slice(-1)` | element | elegant, ES6 | --- > **Conclusion:** > For cross-browser compatibility, use `arr[arr.length - 1]`. > For modern code, `arr.at(-1)` looks much cleaner.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.