Default Parameters Evaluate On Every Call

Default parameter expressions re-evaluate at call time and can read earlier parameters, so counters and dependent defaults behave predictably.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
let counter = 0;

// The default expression runs at call time, once per call, not at definition
function label(name = `item-${++counter}`) {
  return name;
}

console.log(label('explicit'));
console.log(label());
console.log(label());
console.log('counter after three calls:', counter);

// Earlier parameters are visible to later defaults
function span(start, end = start + 5) {
  return [start, end];
}
console.log(span(2));
console.log(span(2, 10));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

explicit
item-1
item-2
counter after three calls: 2
[ 2, 7 ]
[ 2, 10 ]

How it works

The compressed view: all the work sits in the functions label and span, doing all the work.

It builds and returns a fresh value rather than reusing its inputs.

What to watch for

  • The environment needs no preparation beyond having the interpreter or compiler.

Putting it to use

The main signature is written as function label(name = item-${++counter})

Look for the counter after three calls: prefixes once the file starts running; each one ties a printed line to the step that produced it.

The core lines, annotated

return [start, end];

Interactive Tools for This Topic

FAQ

Does `label` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `label`, `span` at load time.