function

Matthias Reuter's picture

Handling the unexpected - Type safe functions in Javascript

Javascript is a weird language. Great but weird. Take functions for example. You cannot only pass any type of arguments, you can also pass any number of arguments. This may be quite disturbing, especially for Java developers. Recently I had a discussion with a Java developer who complained about missing code assistance in Javascript, by which he meant no hint about the type of an argument.

This is of course due to the dynamically typed nature of Javascript. While in Java you denote the expected type of a parameter, and it's the caller's duty to pass the correct type (even more, you cannot pass a different type), in Javascript it's the function's duty to handle the given parameters and do something reasonable with unexpected types. The question arises: How do you write type safe functions in Javascript? Let me explain this by an example implementation to calculate the greatest common divisor of two numbers.Read more

Christian Harms's picture

In-depth guide to javascript functions

You already know how to define or assign functions directly, use multi parameter arguments in anonymous calls and know all the different variants of the function-constructor? Then you won't find anything new about the subtle differences in using functions in JavaScript.

The work title of this article was "Different ways to define JavaScript functions". Some code examples look quite similar but the differences can be important. While I am explaining the different ways to define JavaScript functions, you can test the code directly: install the firebug plugin and use the JavaScript console to play interactively below the article.

Function Statement

In the first example here I define a function to wrap the "window.alert"-function to open the default javascript popup-Message box:

  1. function hello(msg) {
  2.   alert(msg);
  3. }
Read more

Syndicate content