whatstheoutput_

#81: Default parameters and an outer variable

Topic: scope · Difficulty: ★★

function greet(a, b = a + 1) {
  console.log(b);
}
greet(5);
greet(5, 10);
let a = 100;
function useOuter(x = a) {
  console.log(x);
}
a = 200;
useOuter();

Output

6
10
200

Why

Parameters get their own scope, evaluated left to right, so a default value CAN refer to an earlier parameter in the same list: b = a + 1 sees the already-assigned a and computes 6. Passing an explicit second argument (10) skips the default entirely, so b is just 10. Separately, a default value that references an OUTER variable is not computed once when the function is defined — it's evaluated fresh every time the function is called with that argument omitted. By the time useOuter() runs, the outer a has been reassigned to 200, so x defaults to the current value, 200, not the value a held when useOuter was declared.

More scope puzzles

Play today's puzzle →