JavaScript Array Fill() Gotcha: Why You Got Copy-Paste Chaos

💥 JavaScript gotcha of the day: When you think you filled your array with different objects… but JavaScript had other plans 😅 const arr = Array(3).fill({}); // [{}, {}, {}] arr[0].hi = "hi"; console.log(arr); O/p// → [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] You expected: [{ hi: "hi" }, {}, {}] but you got copy-paste chaos 🤯 🧠 Why? .fill({}) doesn’t create new objects — it fills the array with the same reference in memory. So arr[0].hi = "hi" updates all of them, because they’re all pointing to the same object! 🛠 Fix it: Use map() or Array.from() to create unique objects 👇 // ✅ distinct objects const arr = Array(3).fill().map(() => ({})); (or) const arr = Array.from({ length: 3 }, () => ({})); Now: arr[0].hi = "hi"; console.log(arr); // [{ hi: "hi" }, {}, {}] #JavaScript #CodingGotchas #WebDevelopment #Frontend #LearningEveryday #JSFun

  • text

JavaScript keeps reminding us who’s the boss 😂

Like
Reply
Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories