Sunday, 1 September 2013

Getting to know javascript functions the dummy way.

Functions in javascript can be very confusing and hard to grasp for a novice. This is because there are many ways to define and use it in javascript. In this article, we are going to look at what a function is, the various ways in which it can be defined and how it is called.

Generally, in programming situations in which a specific segment of code can be reused most often arise, but instead of usually repeating this piece of code in places which it is needed, most programming languages have syntax to deal with such scenario. This usually include loops, function/method declaration, recursion. In javascript though you can use either of these, but function declaration provides the best alternative in that it is very compact, reduces repetition and aides reuse.

In Javascript, there are three (3) ways in which a function can be declared These include :

  • Use of constructor
  • Normal declaration
  • function as expression
Use of constructor :  A function can be declared by the use of constructor object. This is because every function is an object that inherits from the parent Function object so by using the new keyword, you create an instance of the function and pass the body of the function as string argument to the constructor. Example

var foo = new Function(arg1, arg2, functionBody);

In the code shown above a function that accepts two argument is defined and assigned to the foo variable.
Another way to define a function is by normal declaration. This style is the most popular among javascript developers because it does not suffer from some of the limitations of the use of function constructor suffers from.

function foo()
     //Function body usually consists of one or more javascript statements

The above code shows the normal declaration of functions and is the most advisable way to declare a function. Also,  functions can be declared as an inline expression and assigned to a variable.  This style is popular among script users like jquery.

var bar = function(){ return "Am an inline function";}; 
Now to call any of the above function, simply append brackets and pass in any arguments that the function requires . like  foo();

No comments:

Post a Comment