Magicsheet logo

Array Prototype Last

Easy
25%
Updated 8/1/2025

Topics

Array Prototype Last

What is this problem about?

The Array Prototype Last interview question focuses on extending the built-in functionality of the Array object in JavaScript. You are asked to add a new method, .last(), to the Array prototype. This method should return the last element of the array if the array is not empty, and -1 if the array is empty. This Array Prototype Last coding problem is a fundamental exercise in understanding JavaScript's prototype-based inheritance and the this keyword.

Why is this asked in interviews?

Big tech companies like Google, Meta, and Microsoft use this question to evaluate a candidate's core knowledge of JavaScript. It tests whether you understand how to modify global objects safely and how context (the this binding) works within prototype methods. It's a simple task that reveals if you have a deep understanding of the language's architecture beyond just using modern frameworks.

Algorithmic pattern used

This doesn't involve complex algorithms but rather a direct property access pattern. You check the length of the array (this.length) and return the element at this.length - 1 or a default value. It follows the "Safe Access" pattern, ensuring the code doesn't crash when acting on empty data.

Example explanation

Imagine you have two arrays:

  1. arr1 = [1, 2, 3]: Calling arr1.last() should look at the length (3), see it's not empty, and return the element at index 2, which is 3.
  2. arr2 = []: Calling arr2.last() should see the length is 0 and return -1. By adding this to Array.prototype, all arrays in the application gain this ability.

Common mistakes candidates make

  • Hardcoding the Context: Trying to pass the array as an argument instead of using this.
  • Arrow Function Usage: Using an arrow function to define the prototype method. In JavaScript, arrow functions do not have their own this context, so this would not refer to the array itself.
  • Strict Equality check: Forgetting that 0 is a valid element, so checking if (this[this.length - 1]) might fail if the last element is 0. Always check length instead.

Interview preparation tip

Always use regular function syntax (not arrow functions) when adding methods to prototypes if you need to access the calling object via this. Practice extending other built-in objects like String or Number to get comfortable with this pattern.

Similar Questions