Creating JavaScript Functions the Easy Way - Part 1

Guest Posts Paolo Nikko Nuñal

Passing data in functions is important in many applications as it reduces redundancy in code. This is the most common reason why creating a function is important as it will reduce your code and you don't have to make the same algorithm again. You can do this using a function and return a value once it processes it.

Creating a function is easy in JavaScript and you can do this by declaring:

Syntax:

function functionName;

function functionName;

Functions are useful if you are planning on using the same algorithm all over again. This is useful for a DRY (DON'T REPEAT YOURSELF) approach.

Code


<script>
     addNumbers();
     addNumbers()
     {
         var num1 = 5;
         var num2 = 5;
         var total = 0;
         total = num1 + num2;
         alert(total);

      }
</script>


The code above is the most simplest form on creating a function. You can call the function with the addNumbers() and it will automatically add two numbers. You can also do this by passing parameters.

Code


<script>
     var num1 = 5;
     var num2 = 3;

     addNumbers(num1, num2);

     function addNumbers(num1, num2)
     {
         var total=0;
         total = num1 + num2;
         alert(total);
     }
</script>


From the code above the addNumbers() function receives two parameters num1 and num2, therefore if we want to call the method addNumbers, we need to also pass two variables. In our example above we passed two values namely num1 and num2. After which it gets processed and returns the sum of two numbers.

Note: Always remember to check your function if it has a parameter or not.