Extending Array Prototype in JavaScript

Day 22/30 – Extend the Array Prototype in JavaScript Challenge 🧩 | Build array.last( ) 💻🚀 🧠 Problem: Enhance all arrays so that you can call: arr.last() Rules: Return the last element of the array If the array is empty → return -1 Assume array comes from JSON.parse() 🧠 Example : [1, 2, 3].last() // 3 [].last() // -1 💡 JavaScript Solution : Array.prototype.last = function() { if (this.length === 0) { return -1; } return this[this.length - 1]; }; 🔎 Why This Works Array.prototype lets us add methods to all arrays this refers to the current array instance this.length - 1 gives the last index Time Complexity: O(1) Space Complexity: O(1) ⚠️ Important Note In real production systems, modifying built-in prototypes is usually discouraged because it can: Cause conflicts Break third-party libraries Create unexpected behavior But for understanding JavaScript internals and interviews — this is GOLD 🔥 #JavaScript #30DaysOfJavaScript #CodingChallenge #Prototype #JSInternals #WebDevelopment #LearnToCode #Programming #DeveloperJourney #TechCommunity Extend Array prototype JavaScript JavaScript array last element JS prototype inheritance JavaScript interview questions Modify built-in objects JS Advanced JavaScript concepts

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories