Chapter 5: Functions

5.2 Defining our own Functions

Javascript, like most other programming languages, allows us to define our own functions. To do that, we use the syntax below:

function nameOfFunction(parameters) {
    //Do something
    //return statement (optional)
}

We use the function keyword to declare a function. Next, we write the name of the function, followed by a pair of parenthesis.

Some functions require us to pass data in for them to perform their tasks. The actual values that we provide are known as arguments while the variables used to store them are known as parameters. We pass them to the function by enclosing their values in parentheses ( ) separated by commas.

Some functions return an answer after completing their tasks. We use the return statement to return these answers. After the return statement, the function exits and any code after it that is within the function is not executed. If the function does not return any value, Javascript returns undefined by default.

Let’s look at an example now:

Create a new file in Brackets and save it as chap5.js. Update template.html to link to chap5.js.

Add the following code to chap5.js and refresh template.html in the browser.

function printWelcome(userName) {
    console.log('Hello, ' + userName + '.');
}

printWelcome('Jamie');

In the example above, the function is from lines 1 to 3. The function name is printWelcome, the parameter is userName, and there is no return statement. Within the function, we only have a single line of code that displays a welcome message (line 2).

To use this function, we type printWelcome('Jamie') on line 5. 'Jamie' is the argument that we passed to the function.

If you refresh template.html now, you’ll see

Hello, Jamie.

as the output in the console.

Let’s look at another example. Add the following code to chap5.js.

function addNumbers(a, b) {

    var c = a+b;
    console.log("Statements before the return statement are executed.");
    return c;
    console.log("Statements after the return statement are not be executed.");
}

var sum = addNumbers(1, 4);
console.log('The sum is ' + sum);

This function adds two numbers and returns the result (line 5).

We call the function and assign its result to the variable sum on line 9. Finally, we display the value of sum on line 10. If you refresh template.html, you’ll get the following output:

Statements before the return statement are executed.
The sum is 5

The first output line is displayed because of line 4 in the function. On the other hand, line 6 in the function is not executed as it comes after the return statement.

The second output line is displayed due to line 10.