JavaScript Functions

This tutorial is part of a web programming course for people who have no programming experience.


Programs often repeat some task over and over again. Let's assume that we need to write a program that converts various temperatures from celsius to fahrenheit. Our code might look like this:

var f1 = 10 * 9/5 + 32;
var f2 = 50 * 9/5 + 32;
var f3 = 75 * 9/5 + 32;
var f4 = 100 * 9/5 + 32;

The first line converts 10 degrees celsius to farhenheit and stores the result in a variable named f1. This process is repeated to convert 50, 75, and 100 to temperatures in fahrenheit. Notice how much duplicate code we have above, the equation (aka expression) for converting the temperature is repeated multiple times. Repeating code like this can lead to bugs, say if there is a typo on one of the lines. It can also be difficult to maintain, or update, a program like this because if we find for some reason that we need to change the expression, we'll have to make sure to do it on each line. Instead of repeating the expression, as we have here, we can move it into a function and then use the function whenever we need to convert a number from celsius to fahrenheit.

Functions are reusable groups of commands. You may have worked with functions in a high school math class, and the concept is almost exactly the same in programming: you feed input into a function, it somehow processes the input and returns output. But you'll soon see that functions in programming can vary in ways that differ from functions in math.

Declaring Functions

Let's create a function that converts celsius to farhenheit. The technical term for 'creating' a function is declaring, but programmers will often say defining as well. Here is our first function declaration/definition:

function convertToFarhenheit(tempCelsius){
  var tempFarhenheit = tempCelsius * 9/5 + 32;
  return tempFarhenheit;
}

Let's discuss the syntax for declaring a function. A function declaration begins with the function keyword. Then comes the function name, you can pick any name for the function, but there are some rules that you must follow. For example a function name cannot begin with a number and it cannot include any spaces. Choose your function names wisely, ideally they should describe the purpose of the function. In the example above, I've chosen to name the function convertToFahrenheit, which was a stroke of genius on my part. You should use the camelCase naming convention, which you learned about in the previous lesson when we discussed naming variables.

After the name comes a pair of parenthesis. Inside the parenthesis is the name of the parameter. A parameter is a value that you can 'feed' into the function. In this example, you can feed in a number that represents a temperature in celsius. You can think of a parameter as a variable that can be used inside the function. Instead of saying 'feed in' a value, programmers will more commonly say 'pass in'. You'll see me use 'pass in' when we talk about making use of a function later in this lesson. Note that the name of the parameter in this example is tempCelsius, and that it also uses camelCase.

Then comes a pair of curly braces, and the body of the function goes in between them. The code that we write inside the body of the function will run whenever we use the function.

In the body of the function, the value stored by the parameter is used in the expression to convert it from celsius to fahrenheit. The result of the expression is stored in a variable named result (you can declare variables inside of function bodies) . The second line of code inside the function 'returns' the result, this it the output. return is a keyword in JavaScript and it is used to specify the the output of a function.

Pay attention to the indentation, all the code inside the body of a function should be indented so that you (and your fellow programmers) can easily visualize and read the code. If you left aligned all your JavaScript code it would be extremely difficult to tell where one function ends and another begins. If you don't format your code nice and neat you'll have more bugs, and it will be more difficult to find them, and no other programmer will want to work with you.

Invoking Functions

Once you have declared/defined a function, then you can use it in your program. Here's and example of you could make use of the convertToFahrenheit function:

var f1 = convertToFarhenheit(10);
var f2 = convertToFarhenheit(50);
var f3 = convertToFarhenheit(75);

At this point in our program we have used the convertToFarhenheit function three times. The first time we pass in a value of 10 as the parameter, and the result is stored in a variable named f1. The program does not yet show the results anywhere, but we can add the following lines to display them in the console:

console.log(f1);
console.log(f2);
console.log(f3);

Using a function is called invoking, or calling it. Those terms will become familiar to you very quickly because we'll be invoking/calling lots of functions from here on out. In fact, you have already done so in the previous lesson when you used the alert function (I was calling it a 'command' because we had not yet discussed functions). The alert function is built into JavaScript, which means that you didn't have to define it yourself. There are many, many other built-in functions in JavaScript. And they can save you a lot of time because you don't have to define them yourself, you can simply invoke them whenever you need to make use of the task that they perform. Note that the parameter that you pass into the alert function when you invoke it is meant to be a string, and the function uses by displaying it in the pop up box that appears. You have also already used the prompt function.

In the previous code sample we have used yet another built-in function called console.log, it works in a different way than alert and prompt and we'll discuss it in a minute. But first I want to point something quite subtle out about the previous code sample. Notice that when we invoked console.log we didn't pass in a value (such as 10), instead we passed in a variable that stores a value. My point is that you can use variables as parameters, you don't have to just pass in values. This allows our programs to be extremely flexible and useful.

Let's add code to our program that allows users to convert any temprature from celsius to fahrenheit:

var celsiusToday = prompt("What's the temp today (in celsius)?");

var fahrenheitToday = convertToFarhenheit(celsiusToday);

console.log("Today's temp in farhenheit is: " + fahrenheitToday);

Hopefully you are now starting to understand the power of functions in a programming language. We have created our first useful program, and it allows visitors of the web page to convert any temperature they like from celsius to fahrenheit. You can actually think of a function as a mini program within your program. If you need your program to do something complicated, hopefully you can find a function (mini program) written by another programmer to accomplish the task. In this way, you don't have to reinvent the wheel by defining a function for everything your program needs to do. As you get more experience in programming, you'll find that most of the functions used in your programs are not written by you. And that good programmers have a way of finding and making use of functions written by other programmers (even without understanding the code used inside those functions).

For now, your job is to understand how to create your own functions, but as we move through the course I'll show you other built-in functions that can save you enormous amounts of time.

Parameters

Functions can have more than one parameter. When defining a function like this, you need to separate the parameter names with a comma. Here's a function that you'll probably never need to use, but it demonstrates how to declare a function that takes two parameters:

function someUselessFunction(param1, param2){
  console.log("The value of the first param is: " + param1);
  console.log("The value of the second param is: " + param2);
}

Once you've defined it, you can invoke it and pass in two values that are separted by a comma:

someUselessFunction("sugar", "spice");

Here we've passed in to string values, "sugar" and "spice". Let's invoke it again, but now we'll pass in different values:

someUselessFunction("salt", "pepper");

When you define a function, you can set it up to have as many parameters as you like, just separate the parameter names with a comma. When you invoke a function you should, in theory, make sure to pass in the same number of parameters. There are exceptions but we won't worry about them now.

You can also define functions that have no parameters. In this case you simply omit any parameter names between the parenthesis:

function remind(){
    console.log("Save your work!");
    console.log("Brush your teeth");
}

This is another silly example of a function, but it demonstrates that not all functions have parameters. Note that when defining a function with no parameters, and when invoking it, you still need to include the parenthesis. You just don't put anything in them.

Return Values

Unlike functions in math, functions in JavaScript (and other programming languages) are not required to return a value. You may have noticed that the last three functions we defined did not include a return statement inside the body of the function. If a function does not return a value when it is declared, then there's a subtle difference in the way you invoke it. Let's invoke a few of the functions we've defined in this lesson so that you can see the difference:

var fahrenheit = convertToFahrenheit(100);
remind();

In the first function call (where we invoke convertToFahrenheit) we take the returned value and assign it to a variable named farhenheit (we'll presumably make use of the variable elsewhere in our code). The second function call invokes remind, which is a function that doesn't return anything so there's no need to declare a variable in that statement. Go back and take a look at the definition for each of these two functions and you'll that convertToFarhenheit has returns a variable that was declared inside the body of the function. And you'll see that remind has no return statement inside it's body.

The alert() and prompt() Functions

In the previous lesson we made use of the alert() and prompt() functions, which are built into JavaScript (back then I called them 'commands' because we had not yet learned about functions). Now that we have discussed functions, let's take a closer look at alert() and prompt().

Note that the alert() function requires a parameter (which is the string to be displayed in the pop up window that appears when the function runs).

alert("Hello there!");

The prompt() function requires a parameter, and it returns a value. The parameter is a string that appears in the pop up window, and the input that is entered into the pop up window is what the function returns.

var input = prompt("Please enter some input:");

Summary

Whether you realize it or not at this point, this lesson and the previous one are monumentally important to your education as a programmer. Variables, data types, functions, parameters, and return values are the corner stone of just about any programming language. At this point you should spend a good deal of time practicing by making simple programs to reinforce these concepts and to get familiar with the syntax of JavaScript.

NEXT LESSON: IF Statements in JavaScript