Chained Variable Declarations
One let, const or var statement can declare several variables, separated by commas. Each name in the list is declared with the same keyword:
let width = 4, height = 3, depth = 2;
console.log(width * height * depth);This prints:
24Many style guides prefer one declaration per line, because each line can then be moved, deleted or commented out on its own, but the comma form is valid and common.
Chained assignment is not a chained declaration
Section titled “Chained assignment is not a chained declaration”A different form looks similar but behaves differently: let a = b = 0. Assignment works from right to left, so this runs b = 0 first and then declares a with the result. Only a is declared. b is a plain assignment to a name that was never declared:
function resetBasket() { let itemCount = couponCount = 0; console.log(itemCount, couponCount);}
resetBasket();console.log(typeof itemCount);console.log(couponCount);console.log(Object.hasOwn(globalThis, 'couponCount'));This prints:
0 0undefined0trueitemCount stays inside the function, as intended. couponCount was not found in any enclosing scope, so in sloppy mode JavaScript created it as a property of the global object, and it survives after the function returns. Browsers’ classic scripts behave the same way. The same happens with var and const in place of let.
If an outer scope already has a variable with that name, the assignment changes that variable instead of creating a global, which can be harder to spot:
let total = 99;
function startOrder() { let subtotal = total = 0; return subtotal;}
startOrder();console.log(total);This prints:
0In strict mode
Section titled “In strict mode”Strict mode does not allow assignment to an undeclared name, so the chained form throws instead of creating a global. ES modules and classes are always strict:
'use strict';
function resetBasket() { let itemCount = couponCount = 0;}
try { resetBasket();} catch (err) { console.log(`${err.name}: ${err.message}`);}This prints:
ReferenceError: couponCount is not definedGiving several variables the same value
Section titled “Giving several variables the same value”Either declare the variables first and then chain the assignment, or declare each one with its own value:
let itemCount, couponCount;itemCount = couponCount = 0;console.log(itemCount, couponCount);
let low = 0, high = 0;console.log(low, high);This prints:
0 00 0The first form cannot be used with const, because a const must get its value in the declaration. Variable Scope and Strict Mode cover the accidental global in more detail.
Steve Griffith covers this topic in his video JS Interview - Chained Variable Declarations - Question 18.