Technical skill practice

let vs var in JavaScript: Scope and Captured Loop Bindings

let and var differ in scope and in how loop bindings can be captured. An observable experiment is more useful than assuming that changing the keyword only changes style.

The task

Inspect whether a block variable is visible afterward, then collect callbacks in two loops and call them after iteration has finished.

Runnable Node 22 example

const assert = require('node:assert/strict');

if (true) { var visible = 'block'; let local = 'hidden'; }
assert.equal(visible, 'block');
assert.throws(() => local, ReferenceError);
const fromVar = [];
for (var i = 0; i < 3; i++) fromVar.push(() => i);
const fromLet = [];
for (let j = 0; j < 3; j++) fromLet.push(() => j);
assert.deepEqual(fromVar.map(fn => fn()), [3, 3, 3]);
assert.deepEqual(fromLet.map(fn => fn()), [0, 1, 2]);
console.log(`var=${fromVar.map(fn => fn()).join(',')}; let=${fromLet.map(fn => fn()).join(',')}`);

Expected output and explanation

The var declaration remains visible outside the if block in this CommonJS script, while the let name is not available there. The failed lookup is asserted as a ReferenceError rather than left to crash the example.

The callbacks in fromVar refer to one loop variable whose final value is three. The let loop gives the callbacks the per-iteration binding demonstrated by zero, one and two. Calling the functions later exposes the difference; merely creating them does not print the captured values.

Output from the example

var=3,3,3; let=0,1,2

Pitfall to check

This script does not establish browser global-object behavior: Node CommonJS module scope is its runtime context. Also avoid reading a let binding before initialization; block scope is not a promise that an early lookup safely yields undefined.

Questions, answered

Does const create the same block scope as let?

Both are block-scoped bindings. const additionally prevents rebinding that variable; it does not make every referenced object deeply immutable.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.