How do you know which parameters to set for a javascript function?

80 views Asked by At

Coming from Java, Javascript can be really frustrating.

I'm hoping someone can put this into simple terms for me.

I'm struggling to understand how Javascript programmers know which parameters to pass for a method they're calling - especially when that method is being called as a callback (which in my eyes seems like an added level of complexity).

For example, take the function addEventListener. In this function, a typical use looks like

myDOMItem.addEventListener("click", function(e){...}, false);

In the documentation for this function (hyperlinked to name above) I don't see any mention of this option. Whereas in Java you can easily know if your parameters match the type especially with a good IDE, in Javascript it seems like a huge guessing game or requires serious in-depth knowledge of each function.

How do Javascript programmers do it?

3

There are 3 answers

0
Jim On

In the Mozilla documentation is clearly stated that the function takes four arguments:

  • string (type)
  • function/implementer of EventListener (listener)
  • boolean (useCapture).
  • boolean (wantsUntrusted). Available only for Mozilla/Gecko browsers.

As you can see from the signature, last two parameters are optional and therefore wrapped in brackets:

target.addEventListener(type, listener[, useCapture, wantsUntrusted ]);

To effectively code in JavaScript, you need to organize development environment just like for Java. Java world provides almost endless number of tools for different tasks (UI development, server-side development etc.). The same situation with JavaScript. I would like to avoid ads for IDEs/Editors. Therefore I advise you to use search to find the right tools for your JavaScript-related dev stack.

P.S. Personal opinion. I also came to JavaScript from Java. From my experience, the main problem for Java developers is not the lack of tools but the lack of strict code structure. Since Java gives powerful OOP experience, probably it will be more easily for you to start working with JavaScript in OOP terms. Good development stack for OOP-like JavaScript is provided by the open source project Google Closure Tools.

4
codebox On

The documentation you linked to does show the form in your example:

target.addEventListener(type, listener[, useCapture]);

The type parameter is the string "click", listener is the function object, and useCapture is false.

0
MueR On

We either remember things, or get a good IDE that actually has decent support. Everyone has their favorite, so I won't presume to say that there is a "best" IDE. In my humble opinion, Webstorm is one of the best.