0

Excerpt from the book: "The default value is computed on demand, only when it is actually needed:

const log = console.log.bind(console);

function g(x=log('x'), y=log('y')) {return 'DONE'}

Why when I give one actual parameter to this function it gives return of y, when two arguments it just returns 'DONE', but if I don;t give it any act. parameters it will yield x, y and return statement?

>> g(0)
y
"DONE"

>> g()
x
y
'DONE'

>> g(1)
y
'DONE'

g(1, 2)
'DONE'
Mark
  • 74,559
  • 4
  • 81
  • 117
DevMesh
  • 21
  • 3
  • Possible duplicate of [Set a default parameter value for a JavaScript function](https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function) – UnholySheep Dec 09 '18 at 17:13

2 Answers2

1

This function declaration says:

function g(x=log('x'), y=log('y')) {return 'DONE'}

if no x is passed in, then compute log(x) which is just console.log(x) (this causes "x" to be written to the console); if no y is passed in compute log(y).

If you pass in x or y then there is no need to compute the values, so log(x) (or y) is not computed and you get no console log. If you don't pass in the values, then it calls log() which write the value to the console. Regardless of what you pass in the return value of the function is DONE.

It's a pretty artificial example, but it looks like the point is to demonstrate that if you pass in a value, the right side of the equals is never evaluated.

Mark
  • 74,559
  • 4
  • 81
  • 117
0

The values you are setting to x and y in your function are default values. That means if you do not pass any parameters to function g, it will use the values you set as default x = log('x') and y = log('y').

g(0) is the same as g(x = 0, y = log('y')) so only y gets logged out. You do nothing with 0 inside your function, so only DONE is returned.

g() is the same as g(x = log('x'), y = log('y')) so both x and y get logged out.

g(1) is the same as the first example: g(x = 1, y = log('y')) so only y gets logged out. You do nothing with 1 inside your function, so only DONE is returned.

g(1, 2) is the same as g(x = 1, y = 2) so nothing gets logged out because you do nothing with 1 and 2 inside your function. Only DONE is returned.

Daniel Varela
  • 673
  • 6
  • 13