JavaScript Arrays Stored by Reference

📊 Day 13 – Poll Answer & Explanation ```javascript const a = [1, 2, 3]; const b = a; b.push(4); console.log(a); console.log(b); ``` ### ❓ What will be the output? ## ✅ Correct Answer: **B** ``` [1,2,3,4] [1,2,3,4] ``` --- ## 📌 Step-by-Step Explanation **1️⃣ Arrays are Reference Types** In **JavaScript**, arrays are **objects**. Objects are stored in **memory by reference**, not by value. --- **2️⃣ Assigning `b = a`** ```javascript const b = a; ``` This **does NOT create a new array**. Instead, **both `a` and `b` point to the same array in memory**. ``` a ──► [1,2,3] b ──► ``` --- **3️⃣ Modifying the Array** ```javascript b.push(4); ``` Since **`b` references the same array**, the original array is modified. ``` a ──► [1,2,3,4] b ──► ``` --- **4️⃣ Final Output** ```javascript console.log(a); // [1,2,3,4] console.log(b); // [1,2,3,4] ``` Both variables print the **same updated array**. --- ## 💡 Key Takeaway 👉 **Arrays and objects in JavaScript are stored by reference.** 👉 If multiple variables reference the **same object**, modifying one **affects all of them**. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode

To view or add a comment, sign in

Explore content categories