How to get the last element of an array in JavaScript? (simple and reliable ways)
Hello everyone! I just started learning JavaScript and came across a seemingly simple task. I have an array with data that can be of different lengths. I need to get the last element of this array. It seems elementary, but I want to do it correctly so that the code doesn't break in non-standard situations.
Here's an example of my problem. Let's say I have an array `const fruits = ['apple', 'banana', 'orange', 'grape'];`. I want to get 'grape'. I know you can do `fruits[3]`, but that's a hardcoded index. If I add or remove an element, the index will break. For example:
```javascript
const fruits = ['apple', 'banana', 'orange', 'grape'];
console.log(fruits[3]); // 'grape' — works
fruits.push('mango');
console.log(fruits[3]); // 'grape' — BUT SHOULD BE 'mango'
No answers yet.
Log in to leave an answer