Sunday, September 5, 2010

JavaScript concepts part 2 - functions


JavaScript is a language that's widely used across the web, but it's often not deeply used by many of the page authors writing it. So in this "JavaScript concepts series" I try to introduce some of the deeper concepts of the JavaScript language. This is second article in series that gives you quick overview about JavaScript functions.

Functions: what it is all about?

In many traditional OO languages (Java, C++, OBERON, C#,...) objects can contain data and they can possess methods. In this languages, the data and methods are distinct concepts. We use this methods to alter state of the objects by altering values of object properties (fields).
JavaScript walks a different path.

Functions in JavaScript are considered object. JavaScript will make no distinction between object type like String, Numbers, windows object, custom object and functions. Like other objects, functions are defined by a constructor named "Function". Using this constructor is similar like using constructor in OO language.
Function can have parameters and value of the function (because it is an object) can be assigned to variable, or to an property of the object, returned as function return value, or it can be passed as parameter to another function. All this is possible because function in JavaScript are treated in the same way as other objects. Because of that we say that functions are first-class object in JavaScript.

Example of functions:

function one() {
function two(name, value) {
alert('calculate stuff');
function three() {
return 'stuff';

Functions names

Consider following example:

function findMatix() {
alert('Hello Neo, what is Matrix?');

Does this create function named "findMatix"? No, it doesn't! Although that notation may seem familiar, it's in essence the same syntactic sugar (for which is JavaScript popular) used by var to create window properties (which is described in previous article about JavaScript objects). So that mean that this function create a function instance and assign it to the window property using the function name, as in the following:

findMatix = function() {
alert('Hello Neo, what is Matrix?');

When we declare a top-level named function, a Function instance is created ans assigned to a property (with name of the function name) of window object.

Although this may seem like syntactic juggling, it's important to understand that Functions instances are values that can be assigned to variables, properties, or parameters just like instances of other object type. And it is important to note that disembodies instances are not of any use unless they're assigned to a variable, property, or parameter.

No comments:

Post a Comment