Array Prototype Last | #2619 | LeetCode Solution

Author: neptune | 20th-Sep-2023

Problem : Array Prototype Last | #2619 | LeetCode

Write code that enhances all arrays such that you can call the `array.last()` method on any array and it will return the last element. If there are no elements in the array, it should return `-1`.

You may assume the array is the output of `JSON.parse`.


Example 1:

Input: nums = [null, {}, 3]

Output: 3

Explanation: Calling nums.last() should return the last element: 3.


Example 2:

Input: nums = []

Output: -1

Explanation: Because there are no elements, return -1.


Solution:

        

        Array.prototype.last = function () {

        // Check if the array is empty (has zero length).

        if (this.length === 0) {

            return -1;

        } else {

            // Return the last element of the array.

            return this[this.length - 1];

        }

    };


    /**

     * const arr = [1, 2, 3];

     * arr.last(); // 3

     */




Explanation:

Let's break down the code step by step:


1. We define a `last` method on the `Array` prototype.


2. Inside the `last` method, we first check if the array's length is equal to `0`, indicating an empty array. If it's empty, we return `-1`.


3. If the array is not empty, we use `this.length - 1` to access the last element of the array and return it.


Now, you can call the `last` method on any array, and it will return the last element or `-1` if the array is empty, as demonstrated in the example usage.