JavaScript Corners – Part 3
I was busy reading ES spec today, and the following question popped into my head: at what point are default parameters evaluated?
To answer this question, I wrote the following script:
function f(x = (console.log('a'), 'b')) { console.log(x); } f(); f(); f('c');
If default parameters are evaluated when the function is declared, then we would expect 'a'
to appear once in the terminal output.
On the other hand, if the default parameter expressions are evaluated when the function is called, then we would expect 'a'
to appear two or three times, corresponding to each time the function is called, and whether the default parameter expression is evaluated even when an argument is provided.
What do you think the output is? I won’t show you here… you can run the snippet yourself in a REPL to see if you’re correct or not.
As I did last time, I’ll leave you with this mind-bending challenge: what does the following do?
const a = 'b'; const b = 'c'; const d = 'e'; const x = 'd'; function f({ x = a }, { [x]: y = [x] }) { console.dir(x); console.dir(y); } f(x, { b, d }); f({ x }, { b, d }); f({ x }, b, d);