How To Get Last Element Of Array In Javascript

In this blog post, we will learn how to get the last element of an array in JavaScript. We will go through a few different methods to achieve this, all with their own pros and cons.

Method 1: Using Array Length Property

The easiest and most straightforward method to access the last element of an array is by using its length property. The length property returns the number of elements in the array. Since the index of the first element is 0, we can use the length property to calculate the index of the last element by subtracting 1.

Here’s an example:

    const numbers = [1, 2, 3, 4, 5];
    const lastElement = numbers[numbers.length - 1];
    console.log(lastElement); // Output: 5
    

Method 2: Using Array Pop() Method

We can also use the pop() method to get the last element of an array. The pop() method removes the last element from an array and returns that element. Keep in mind that using this method will modify the original array.

Example code:

    const numbers = [1, 2, 3, 4, 5];
    const lastElement = numbers.pop();
    console.log(lastElement); // Output: 5
    console.log(numbers); // Output: [1, 2, 3, 4]
    

Method 3: Using Array Slice() Method

If you want to get the last element of an array without modifying the original array, you can use the slice() method. The slice() method returns a shallow copy of a portion of an array into a new array object. By providing -1 as the start index parameter, we can get the last element of the array.

Example:

    const numbers = [1, 2, 3, 4, 5];
    const lastElement = numbers.slice(-1)[0];
    console.log(lastElement); // Output: 5
    console.log(numbers); // Output: [1, 2, 3, 4, 5]
    

Conclusion

In this blog post, we have explored three different methods to get the last element of an array in JavaScript: using the array length property, using the pop() method, and using the slice() method. Each method has its advantages and drawbacks, so choose the one that best suits your needs and coding style. Happy coding!