logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

Functions

Functions are blocks of code designed to perform a specific task. Functions can help organize the code, avoid repetition and reduce the complexity of the code.

Let's start with a simple example.

                    
    
    // Creating the function

    function sum_numbers() {
        var num1 = 5;
        var num2 = 2;
        var sum  = x + y;
        console.log(sum);   
    }

    // The function is only executed after being invoked:

    sum_numbers(); // The console will show 7

                    
                

Some important observations about what we've just done:

Function arguments

The arguments of the function are like variables that can be used inside the functions. In the example above our function will always sum 5 + 2, which is not very useful. By using arguments we can make it dynamic and sum different numbers everytime.

                    

    function sum_args(num1,num2) {
        var sum  = num1 + num2;
        console.log(sum); 
    }

    /* Now when invoking the function we can use any numbers we want: */

    sum_args(10,25); // The console will show 35

    sum_args(1000,375); // The console will show 1375

    sum_args(-2,47); // The console will show 45



                    
                

The return statement

Our function is now dynamic but it's performing only one task: sending the result to the console. This can be useful for testing purposes but not more than that. It would be good if our function could return the value so we could do anything we want with it.

That's what the return statement will do:

                    

    function sum_args(num1,num2) {
        var sum  = num1 + num2;
        return sum; 
    }

                    
                

Now we can do anything we want with it, like using in other calculations and sending the result to an HTML element.

                    

    var average = sum_args(6,10) / 2;

    console.log( sum_args(13,21) );

                    
                

Can you sum -27 and 55 and show the result in the element below?

This element has id="sum_result"

Contents