Introduction To Functions

Open the project folder

In our starter files, open the index.html page from this lessons folder:

01.JavaScript Basics > 13.Introduction-to-functions

JavaScript Functions

Next, we have JavaScript functions. A function like a task, or, a set of tasks grouped together.

For example, in our upcoming Speedy Chef project, we will have many functions which perform a task, such as generating a new pizza, creating an order, or checking if the oven is full. These functions can run immediately, or more often, when we call upon them.

As with arrays and objects, we will have a more detailed functions section coming up, but for now, having a basic function knowledge will help us with some other steps. Functions, like arrays and objects, also fall into the object type group.

Over to the starter files, we have 2 arrays at the top here which we can ignore for now:

let bread = ['flour', 'yeast', 'salt', 'water'];
let brownies = ['butter', 'chocolate', 'flour', 'eggs', 'sugar'];

Creating a function

Create a function below this using the function keyword:

function

Followed by a name we want to give it. This is the name we call when we want to run the code inside the function. Let’s look at a random number generator:

function randomNumber

Immediately after the name, we pass in brackets, called parenthesis:

function randomNumber()

This can be used to pass some extra information to the function, more on this in as moment though.

The last part is the curly braces, which is the function body:

function randomNumber() {

}

These braces contain the code to execute when we call the function. These can be thought of as a set of gates to contain all the code inside, and this is what is called a function declaration.

We can place inside any code we want, a simple example is to create a browser pop up, called an alert:

function randomNumber() {
  alert('hey');
}

This sends the user a message, and you will probably have seen these before in the browser. To run this code, we call it by the function name:

Calling a function

function randomNumber() {
  alert('hey');
}
randomNumber();

This will now create an alert in the browser when loaded.

The return statement

Another example could be a calculator to convert a dog age to human years:

const dogAge = 3;

function dogToHuman() {
  const humanEquiv = dogAge * 7;
  return humanEquiv;
}
// call function
dogToHuman();

Notice the return keyword in the above function, this will send back, or return a value from the function.

If we reload the browser, we don’t see anything happen because we have not told the function to do anything. The first example has an alert which was a visible clue that the function was ran correctly.

But, for this one, we have not told it to alert, to console log, we just return an age. To see this, we could pass this function call directly into a console log, or even store it in a variable:

const result = dogToHuman();

This variable can then be used for anything which we want:

const result = dogToHuman();
console.log(`My dog is aged ${result} in human years`);

This return keyword can only be used once in a function, since it signals that the function should stop running. There are some exceptions such as when a function contains an if/else statement which we will learn about later. But generally, return is the end of the function and the code after it will be ignored, and we can see this if we place an alert after it:

function dogToHuman() {
  const humanEquiv = dogAge * 7;
  return humanEquiv;
  alert('hey');
}

Give this a test and the alert will not run since it comes after the return.

Function parameters

Using the functions brackets (parenthesis) that follow the function name, we can pass in extra information to the function:

dogToHuman()

In these brackets, we set up one or more parameters, which you can think of as variables.

Instead of using the dogAge variable, the function can now be passed this data as a parameter:

// const dogAge = 3;
dogToHuman(dogAge)

But where does this parameter now get the value from?

Function arguments

We pass it when we call the function, and this value is called an argument:

const result = dogToHuman(5);

This makes our function more reusable since we can call it multiple times with different arguments passed to it. Each result can then be stored into a variable.

There are quite a few keywords covered here, and you don’t need to remember them at this stage.

People often confuse parameters and arguments and use them interchangeably. It’s not a huge problem, but just to clarify, parameters are the variables or placeholders in our function declaration, and we can access them inside of the function body, which is inside the curly braces.

Arguments are the actual values we use when we call the function, such as our number of years in this example.

Let’s take this a little further, using the 2 ingredients arrays at the top of the index.html page. First, clean up any code from previous examples by commenting it out or removing.

Looking at the bread and brownies arrays, imagine we wanted to test if any of these contain a certain ingredient, to check for allergies. A function could help with this, in combination with the includes method we looked at earlier:

let bread = ['flour', 'yeast', 'salt', 'water'];
let brownies = ['butter', 'chocolate', 'flour', 'eggs', 'sugar'];

function checkAllergies(recipe, ingredient) {
  const hasIngredient = recipe.includes(ingredient);
  return hasIngredient;
}
console.log(checkAllergies(bread, 'flour'));

Let’s break this down. We begin by creating a function which takes in a recipe and ingredient:

checkAllergies(recipe, ingredient);

The recipe is the array, and the ingredient is the single value inside the array we want to find. Inside the function body:

const hasIngredient = recipe.includes(ingredient);
return hasIngredient;

The includes method will check if the single ingredient is present in the given recipe, returning a true or false value.

After we create the function, we then call it with the real values of bread and flour and log the returned value to the console:

console.log(checkAllergies(bread, 'flour'));

This case checks if the value of flour is contained in the bread array. And these values can be swapped with others.

You should be starting to see the power of functions, but there is a lot more to functions that we will discover. One of the big benefits of functions is they are re-usable. If we have code in our program that is repeated multiple times, we could move that code in to a function, and call the function in place.

The function can also be passed different values in the form of arguments which we just discovered.

You can also think of them as building blocks, each one is assigned a particular task so they can make our code more organised.

Functions can also be in many other forms, these examples are the more traditional form of a JavaScript function, there are other types available.

As a general guide, if possible, it is better to keep functions small if possible, and focusing on one task. This makes it easier to know what a function is doing, it makes it more reusable, and also helps with debugging since if there is an issue, we can narrow the focus to a small piece of code.