Creating JavaScript Functions the Easy Way - Part 2

Guest Posts Paolo Nikko Nuñal

Functions are great for shortening your code, and in our previous tutorials we have managed to discuss how functions work. However, in this tutorial you are going to learn how to call a function by declaring it as a variable. Most Java programmers do function the old fashion way like:

Code:

 function numbersArray(array){
      myArray[0] = "Toyota";
      myArray[1] = "Ford";
      myArray[2] = "Honda";
      myArray[3] = "Suzuki";
}


However, you can also do it in another way by storing the function inside a variable.

Code:

 var name = function();


The above code is the same as this one:

Code:

function name(){}


Another advantage of storing functions in a variable is the fact that it is easy for you to call and use throughout your program. Here's another example.

Code:

<script>
     var name = function(){
         alert("John Doe");
     }
     name();
</script>


From the example above, we have called the function name() that accepts no parameters and displays an alert string named "John Doe"). You can also pass parameters.

Code:

<script>
    var myName = function(name){
        alert(name); 
    }
    myName("John Doe");
</script>


 

From the code above, we call the function myName that accepts one parameter. We pass the string "John Doe" in which it invokes the function and alerts the name. You can also use as many parameters as you want provided that the function you are calling matches the amount of parameters that is passed.