Closures & scope · Output question
JavaScript default parameters at call time
A default parameter reads a variable outside the function. Predict its value across calls after the outer variable changes.
let tone = "warm";
const speak = (message = tone) => message;
tone = "cool";
console.log(speak());
console.log(speak("warm"));What gets logged?
Choose an output before opening the walkthrough, or check your answer in practice mode.
Reveal the answer and execution trace
cool
warmDefault parameter expressions are evaluated when a call needs the default. An explicit argument bypasses it.
- Line 3. tone is updated before either call.
- Line 4. speak receives no argument, so it evaluates tone and uses "cool".
- Line 5. This call supplies "warm" directly.
Reference: Default parameters on MDN.