JavaScript Closures and the Event Loop Challenge

Time, tide, and JavaScript wait for none. Let's look at a classic interview-style challenge that proves this with Closures and the Event Loop. The Challenge: Print 1 after 1 second, 2 after 2 seconds, and so on, up to 5. The most intuitive (but flawed) approach using var: function x() {  for (var i = 1; i <= 5; i++) {   setTimeout(function () {    console.log(i);   }, i * 1000);  }  console.log("Hello AI World"); } x(); The Actual Output: Hello AI World 6 6 6 6 6 🤯 Why the Wrong Output? The fundamental reason the original code fails is due to closures interacting with var's function scope. The correct output is achieved by replacing var with let because let creates a block-scoped variable for each iteration, which the closure can then correctly capture. #JavaScript #ReactJS #WebDevelopment #learning

To view or add a comment, sign in

Explore content categories