NoName84 NoName84 - 9 months ago 52
Javascript Question

JavaScript. How can i use the single parameter without calling the function?

I am having a question that I find it difficult to understand.

The question is about JavaScript functions and it’s parameters.

When we write a function we can give it from one to various parameters, for example

function myCustomFunction(parameterOne, parameterTwo)

Then we can use these parameters as arguments when we are calling the function, for example

myFunction("hello", "World")

and it will give us the values
when we call the function.

However there is one thing that I see a lot of people making that I don’t really understand and that is, some people when they write a function they are passing a parameter (
) or (
) which I know they stand for element or event. They are using the parameter in the function without calling the function for example

el.className = "something"
e.className = "somethingElse";

What is the purpose of that parameter when we create a function and what can I really do with it?

P.S Please explain as detailed as possible.


Answer Source

You don't show a specific example, but it sounds like you're talking about a function that is passed as a callback to another function. In this case, you're declaring a function that is going to be called by some other code. You pass that function as an argument and then, sometime later, that other code calls your function and passes it the desired arguments.

Here's an example:

document.getElementById("test").addEventListener("click", function(e) {
   // this function is called by the browser when the click event occurs
   // the argument `e` is an event object passed by the browser

What is the purpose of that parameter when we create a function and what can I really do with it?

When passing a callback function, you have to know what the "contract" is for this API (usually via some documentation). That contract will describe what parameters will be passed to the callback function when it is called. For the click event listener above, the contract is that the first argument passed to the callback function will be an event object that has the properties described here. When you declare your callback, you then declare it with arguments that match what will be passed to the callback. That particular API also sets the this pointer to be the object that dispatched the event (in the above example, the DOM object that was clicked on).

In a strongly typed language like C++, the compiler would enforce that you declared the exact right arguments on your callback function. In Javascript, there is no such enforcement so you give the arguments appropriate and meaningful names and put them in the right order for the code to be clear and to work properly. Just remember that it is the caller of the callback (not you) that determines what arguments the callback function will get.