JavaScript – A Different Beast, Part 3: Functions

Previous topic in this series: Types and Type Conversion

This is the third part of my tutorial on JavaScript. Focus of this series is to introduce developers who are comfortable with other programming languages like Java or C to the idiosyncrasies of JavaScript. Basic JavaScript knowledge is assumed, but is not necessary as the code samples are simple and self-explanatory.

Topics:

  1. A different beast
  2. Types and Type Conversion
  3. Functions
  4. Scopes and Scope Chain
  5. Closures
  6. Objects without Classes
  7. Inheritance without Classes
  8. Arrays, Maps and the for..each loop
  9. Literals and JSON
  10. Dynamic Programming, Exceptions and Module Pattern

JavaScript is a functional programming language (among many other things), which means that functions are treated as first class objects. In plain-speak, it means that functions are treated just like any other value or an object. In fact, one can even pass functions around just like one passes around data. Or you can write a function that creates other functions and many more stuff like that – some of them appear quite weird initially! We will get to all these stuff, but first, the basics.

Code 2.1 below shows all the ways in which one can create functions in JavaScript, followed by explanations.

//Code – 2.1:  Creating and calling functions
//a) the straightforward syntax
function foo(param) {
	console.log('Why is it always foo?',param);
}
foo(1000); //calls foo

//b) function as an object
var bar = function(param){
	console.log('Darn! Its either foo or bar!',param);
}
bar(444); //calls the function referred to by the variable ‘bar’

//c) using the Function constructor
var add=new Function("a", "b", "return a+b;");
console.log(add(3,4)); // produces 7
//bit strange? Will be clearer after chapter-3 on Objects

//the all familiar typeof
console.log(typeof(add), typeof(foo), typeof(bar)); //prints ‘function’
console.log(add instanceof Function); //true
console.log(foo instanceof Function); //true
console.log(bar instanceof Function); //true
//hereby proved that all of the function creation forms actually do the same stuff!

a) The straight-forward syntax is the simplest of all. It just creates a function in the current scope.

b) The ‘function as an object’ syntax is quite common too. This has some differences from the previous approach when it comes to object oriented programming in JavaScript. More about this in chapter-3.

c)  Using the ‘Function’ constructor – This is a convoluted way of doing the same thing, but has its own merits in the form of dynamic programming. In case you haven’t noticed, the arguments to the Function constructor are all strings. This allows clever programmers to form strings on the fly and create an executable function which can then be used like any other function. Such techniques are often used in developing toolkits or libraries.

The last few lines of the above example shows that all these functions are actually made up of the same stuff – means to the same end. Interestingly, one can even create functions without any name. Such functions are called anonymous functions. See code-2.2 to see two examples for anonymous functions.

//Code – 2.2: Anonymous function
//a) declaration and invocation in one go!
(function(a,b){
     console.log(a+b);
})(2,5); // prints 7

/*b) Registering an anonymous function as a click event handler

button1.onClick = function() {
    alert(‘Clickety click..’);
}
*/

The trick here is the clever use of parenthesis. The vanilla version of function syntax(approach in code-2.1(a))  is used here, but the whole function definition code is wrapped around in a pair of parenthesis making the whole thing a reference to the anonymous function. The last two parenthesis – the (2,5) – is a call to the function with 2 and 5 as arguments, just the same way you would invoke a reference as shown in code-2.1(b). By the way, ‘(..)’ is actually an operator – called the function call operator.

This technique looks useless at first glance since the function can be used only once. However, this technique, along with closures is the cornerstone for writing plug-ins in many toolkits like jQuery and YUI. (We will be covering closure shortly). The most common usage for anonymous functions is as shown in the second half of the code (b). It is very convenient to create and register such event handling functions. (The same pattern is used in UI programming in Java and C# also, using anonymous classes)

About Rahul Mohan

Technical researcher interested in model-driven development of enterprise business applications. Passionate about web technologies and a huge admirer of open-source especially in the Java landscape. When I am not doing any of the above you can find me with my camera (www.flickr.com/photos/rahulmohan/) or listening to music. (In fact, the title of the blog is inspired by Led Zeppelin's Physical Graffiti. )

Posted on May 12, 2011, in JavaScript, Tutorial and tagged , , , , , . Bookmark the permalink. 7 Comments.

Leave a comment