JavaScript scope and reassignment gotchas

If you think variable types only affect scope and reassignment… 👀 This might surprise you 😅 👉 Same code… different output for (let i = 0; i < 3; i++) → 0 1 2 ✅ for (var i = 0; i < 3; i++) → 3 3 3 😳 👉 Why? let → block scoped (new binding per iteration) var → function scoped (single shared variable) By the time setTimeout runs… the loop is already finished 😬 👉 So all callbacks use the same final value 👉 Small keyword change… completely different behavior 💡 Be honest 👇 What did you expect for the second loop? 😅 How would you fix the var version to print 0 1 2? 🤔 Comment your answer 🔥 Follow for more dev scenario concepts 🚀 #JavaScript #Developers #WebDevelopment #Coding #AsyncJS #Relatable #Learning

  • text

To view or add a comment, sign in

Explore content categories