for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 100); }
The variable i is declared with var, which has function scope. By the time the callbacks run, the loop has finished and i is 3. So all callbacks print 3.
for (let i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 100); }
let inside the loop.Using let creates a new binding for each loop iteration. Each callback closes over its own i, so the output is 0, 1, 2.
function fetchData(id, callback) { setTimeout(() => { callback('Data for ' + id); }, 100); } for (var i = 1; i <= 3; i++) { fetchData(i, function(data) { console.log('Received:', data); }); }
id is passed to the callback.The id is passed as an argument to fetchData and used inside the callback. Each call has its own id, so the output matches 1, 2, 3.
function doWork(callback) { setTimeout(() => { if (callback) { callback(null, 'Success'); } }, 100); } doWork();
The function checks if callback exists before calling it. Since doWork is called without arguments, no callback is called and no error occurs.
var x = 1; function outer(callback) { var x = 2; callback(); } outer(function() { console.log(x); });
The callback is defined in the global scope where x is 1. Inside outer, x is 2 but the callback does not close over that variable. So it prints 1.
