how does the function know that it should return the event object to that argument if there is one?
It doesn't examine the target function for arguments, it just passes the argument(s) that it is designed to pass. It's up to the function to either use them or not.
where does the event object go if there is no argument mentioned?
Nowhere. If the function doesn't expect an argument then any argument sent to it is simply ignored.
Forget event handlers and other callbacks for a moment, you can test and observe with simple functions. Consider this function:
function test1 (x) {
console.log(x);
}
And you call it with an argument:
test1('test!');
Now, change the function to this:
function test1 () {
console.log('foo');
}
You can still call it with an argument:
test1('test!');
That argument is simply ignored.
It's up to the caller of the function to pass arguments, and it's up to the function to accept/use arguments. JavaScript doesn't check that these things match. (TypeScript does though.) In the case of event handlers or callbacks for built-in functionality (like calls to .find()
or .map()
for example), the implementation passes the arguments that it's documented to pass when it invokes the callback. But there's no rule that you must expect or use those arguments.
Edit:
Since you updated the question to include...
How can I write my own function which returns the value to one of the parameter?
Any function you write can expect any arguments you like. For example, let's say you want a function to expect a function as an argument:
function test2 (callback) {
callback('foo');
}
If this test2
function is meant to be used by other developers then you would include in its documentation how you plan to invoke the function it receives as an argument. (That you plan to call it with a single argument of a string value.)
Then when using your test2
function, you'd supply that function parameter:
test2(function (x) {
console.log(x);
});
Event handlers and other built-in functions that expect callbacks document how they plan to use those callbacks.