08 - Functions in Javascript

The workhorses of Javascript

As mentioned earlier, almost everything in Javascript is an object, including functions. However, functions are not just a bagful of variables containing properties; functions are the work-horses in Javascript, they are the means of getting work done. Although object oriented concepts are a little beyond the scope of this tutorial, do keep in mind that functions serve as the main abstraction facility as well as the implementation mechanism. In Javascript, procedures, methods, constructor, classes and modules are all fused into functions. Once you have grasped the concept of functions and are fairly familiar with its workings, be sure that you have mastered a significant portion of Javascript.

The Block

Before you move on to understanding functions you have to understand blocks. Blocks are nothing but a pile of code, statements, grouped together. Blocks start with the begin symbol ‘{‘ and the end symbol ‘}’ denotes the end of the block. Blocks allow the code inside the bracket to be executed together. Here are a few ways demonstrating blocks and function calls:

// immediately invoked function expression

;!function() {

   var    Succeeded = false,
              cake = false,
              satisfaction = 0,
              isLie,
              note;
} 

 

// Block used part of a function expression

var isLie = function(val) {
       
      returnValue == false;
}

 

// Block used as part of a conditional statement

if (isLie(Cake)) {
     triumph = true;
     makeNote('Yay Success');   
     satisfaction += 10;
}

 

// Block used as part of a function declaration

function makeNote(message) {

          note = message;
}

 

Functions are essentially named blocks which you, the developer, can call on demand. So when you code:

var isLie = function(val) {

           returnValue == false;
}

You called it once, it gets executed once. But this function gets executed as many times as you call it.

function makeNote(message) {

       note = message;
}

 

makeNote(“Awesome Success”);

makeNote(“Epic Success”);

Functions have to be called

What you will have to keep in mind is that just because you have written a function will not necessarily mean that that function will be executed in the runtime of the program. Functions once coded, will have to be called, then only they are executed.

Parameters

Functions can have parameters. In the above makeNote function message is a parameter. Functions can have multiple parameters.

function MyFunction(parameter1, parameter2, parameter3) {

// function code

}

You can call/invoke the function this way:

myFunction(value1, value2, value3);

Variable Scope in Functions

Function parameters are variable names and for the purpose of your mental sanity it is better to use different variable names when invoking the function. Another point that you will have to keep in mind is variable scope. Although we had discussed this in an earlier chapter, in order to reduce confusing code and thus your debugging time, you need to pay attention to variable scope. Here is a sample code for you to munch:

<html>
 <head>
   <script type = 'text/javascript'>
     var aNewVariable = "is global.";
     function DoSomething(incomingBits) {
     alert("Global variable within the function: " + aNewVariable); 
     alert("Global variable within the function: + inCommingBits");
     }
   </script>
 </head>
 <body>
   <script type = 'text/javascript'>
     DoSomething("is a local variable");
     alert("Global variable outside the function: " + aNewVariable);
     alert("Global variable outside the function: + inCommingBits");
   </script>
 </body>
</html>

Do take a second look at the above code for it shows the declarations for global & local variables as well as their scope within and outside a function. Note the naming convention followed for variable names, they are logically separate.

A function Return a value

After a function has finished executing its code, it can throw out a value to the caller by using the return keyword. Consider the following:

function MultiplyNumbers(x) {

    return x * 2;
}
     var aNumber = 10;
     var Result = MultiplyNUmbers(aNumber);
     alert(Result);

As you can see, the function MultiplyNumbers takes an input value which is assigned to variable x.

        function MultiplyNumbers(x)

The function executes its code and creates a variable called aNumber

        var aNumber = 10;

The code then creates a variable called Result to which is assigned the return value of the function which takes aNumber as its argument/parameter.

Do note that once the java interpreter comes across the keyword return in your code, it will stop further execution of code which is below the return keyword.

Function Literals

So far, all the functions that you have seen have been formally defined. However, in Javascript, functions need not be formally defined. In Javascript there are a type of functions called unnamed / anonymous function. An unnamed function is defined in this way:

var MultiplyNumbers = function(number1, number2);

Unnamed functions are heavily used in object oriented javsacript programming as handlers for events, a subject we will cover later.

Closures

In javascript nested functions have access to the variables declared outside the nested function. So when we talk of closure, it is in reference to the existence of a variable outside the normal scope of a function’s execution. Most of the time closures are created by accident and are the root cause for bugs such as memory leaks.

Consider this code showcasing a closure:

 

function MyFunction() {
  var aNumber = 10;
  function ShowNumber() {  

         alert(aNumber);
  }

      Return ShowNumber;

} 

var CallFunction = MyFunction();

callFunction();

You are right in thinking how can the variable aNumber can be accessed by the nested function ShowNumber? Because this is Javascript. It supports this kind of ‘risky’ behaviour. What you should also notice is that the function CallFunction is created in the global context and contains and can access both variables aNumber as well as ShowNumber.

Closures are normally used to emulate private methods inside objects, although they can be used, as stated earlier as event handlers. Closures are an advanced topic and we will taken it up much later in this tutorial. In the meantime, do google and read it up.

Like us on Facebook