I have following code:
function f() {
//...do stuff with arguments
//and return something...
}
f(root,
f(child1),
f(child2,
f(subchild1),
....
),
);
I want to know when the root level of 'f' is called, so I introduce a flag as an argument:
f(root, '-r',
f(child1),
f(child2),
//...
)
My question is: Is there a way to know when 'f' is called on the top level "f(root,...)" without adding additional arguments?
Yes, it matters. The arguments must be given in the order the function expects them.
Functions in JavaScript are 'first class', which means they are treated like any other variable — including being passed to or returned from other functions. When they're passed as an argument to another function, they're known as a 'callback' — to be called when the other function is ready for them.
The important takeaway here is that the name of the argument doesn't have any significance. The only thing that matters is the order in which the arguments are passed.
f refers in order to the top level anonymous function, then to the inside function returning 1 and finally to the second function returning 2. So when we call f the value 2 is returned.
No, you have no way of telling, in code within f
, that its return value isn't being used to build an arguments list for a subsequent call to f
. (Or indeed, that its return value is or isn't being used for any particular thing, or nothing, at all.) It's not an unreasonable question, but that information just isn't available to f
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With