DevMesh
DevMesh

Reputation: 19

Elif me this example from Exploring ES6 please

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'

Upvotes: -1

Views: 72

Answers (2)

dev
dev

Reputation: 893

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.

Upvotes: 0

Mark
Mark

Reputation: 92471

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.

Upvotes: 1

Related Questions