JavaScript ArrayWrapper Class Implementation

🚀 Day 29/30 – Design ArrayWrapper Class in JavaScript 🧠 📌 Problem : Create a class ArrayWrapper that ✅ Feature 1 – Addition (+ operator) When two instances are added: obj1 + obj2 It should return the sum of all elements in both arrays. ✅ Feature 2 – String Conversion When calling: String(obj) It should return: "[1,2,3]" Exactly like a normal array string format. 🧠 Example const obj1 = new ArrayWrapper([1,2]); const obj2 = new ArrayWrapper([3,4]); obj1 + obj2; // 10 String(obj1); // "[1,2]" String(obj2); // "[3,4]" 💡 JavaScript Solution class ArrayWrapper { constructor(nums) { this.nums = nums; } valueOf() { return this.nums.reduce((sum, num) => sum + num, 0); } toString() { return `[${this.nums.join(",")}]`; } } 🔎 Why This Works : 🔹 valueOf() JavaScript calls valueOf() when using the + operator on objects. So: obj1 + obj2 Becomes : obj1.valueOf() + obj2.valueOf() Which returns the total sum. 🔹 toString() When String(obj) is called, JavaScript invokes: 🔹 obj.toString() So we return a formatted array string. 🧠 What This Teaches ✅ Object-to-primitive conversion ✅ Operator overloading behavior in JS ✅ valueOf() vs toString() ✅ How JavaScript handles coercion internally ✅ Custom class design ⚡ Real-World Insight Date objects behave with + Number objects convert to primitives Custom libraries control serialization Understanding this means you now understand JavaScript coercion rules deeply. #JavaScript #30DaysOfJavaScript #CodingChallenge #OOP #JavaScriptInternals #FrontendDevelopment #WebDevelopment #SoftwareEngineering #LearnToCode #Programming #InterviewPrep #JSDeveloper #CleanCode #100DaysOfCode JavaScript valueOf example Override toString JavaScript class Operator overloading JavaScript JavaScript object to primitive conversion Custom class JavaScript interview question JavaScript + operator with objects Implement ArrayWrapper JS JavaScript coercion explained

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories