User Defined Functions

Writing your own functions gives the ability to reuse code.

Almost all programming languages allow us to write our own functions. In Javascript, the syntax is: function name (params) { // Your code with optional return value }

Let's say we need to do something over and over in our program - perhaps decide how many zeros are in a quadratic equation given a ,b ,and c. Rather than do the math over and over, we can create a function and return either 0, 1, or 2.

// Determine how many real roots exist
function descriminate(a, b, c) {
    let desc = Math.pow(b, 2) - (4*a*c);

    if (desc < 0)
        return 0;
    else if (desc === 0)
        return 1;
    else
        return 2;
}

This would allow us to make decisions or act on the return value of 0, 1, or 2. We could print it, use it for other math, or ignore it completely.

Ex. 1 - No return value

If your function does not have a return call with a value, the result is undefined. Here's a simple example of a function that doesn't return anything:

Ex. 2 - No parameters

It isn't often that a user-defined function has zero parameters. However, it can be done. Here's one that shouts the current time (it prints it to the console). No parameters, no return value.

Ex. 3 - Parameters

Here's a function that takes two parameters, base and exponent. It prints the answer to the console. Again, no return value.

Ex. 4 - Optional Parameters

In example 2, above, the time is output in 24-hour "military" time. Perhaps we only want it to do that if we ask it to. We can have a parameter militaryTime that is false by default but if we pass true as a parameter to the function, it prints in 24-hour format.

Notice how we defined the parameter to our function: shoutCurrentTime(militaryTime = false) This defines the parameter and sets it to false, unless we set it to something else.

Ex. 5 - Return Values

The true strength of a function is the ability to return an answer. It could be a modification of the parameter(s) passed into the function or a completely unrelated piece of data. The return keyword breaks out of the function, no matter what is happening, and sends whatever data you want to return. Note: if you need to return more than one piece of data, you must return it in an array or object.

Many examples in one:

Last updated