[Easy] LeetCode JS 30 - 2619. Array Prototype Last

March 7, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2619. Array Prototype Last

Question Prompt

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.

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

To solve this question, we need to understand JavaScript’s prototype mechanism. JavaScript is a unique language where objects, like arrays, are built on something called 'prototypes'. Think of a prototype as a blueprint. Every array inherits properties and methods from this blueprint.

Our goal is to modify this blueprint so that all arrays automatically gain the .last() method. We can do so by adding a new property called last to the prototype and assign it a function. This function will be the code that runs when you call .last() on an array.

Inside the function, we first check if the array has any elements (this refers to the array itself). If there are elements, we calculate the index of the last element (remember, array indexes start from 0) and return the element at that index. If the array is empty, we return -1

Array.prototype.last = function () {
  // check if the array is not empty
  if (this.length > 0) {
    return this[this.length - 1]; // Return the last element
  } else {
    return -1; // Array is empty
  }
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee