JavaScript functions explained

New tutorials sent to your inbox 💌
ballet doodle
Prerequisites
This tutorial assumes that you are familiar with declaring variables and working with the data types Number, String and Boolean. Please check out the tutorial on JavaScript variables and data types if you haven't already done so 🙂.
What is a function?
A function is a block of code that performs a specific task, just like a cooking recipe with a list of steps. A recipe provides instructions for a single, specialised dish, just like functions provide calculations for a single, specialised purpose.
How do you write a function
function coolFunction(parameter1, parameter2, parameter3){
  // cool function code goes here
}
A JavaScript function is created by using the keyword function, followed by the name we wish to call the function. Like we do with variables, functions should be given descriptive names, and written in camelcase. We then use brackets after the function name to define our function's parameters. Parameters are just names given to the pieces of information we will eventually pass to the function for it to use to perform it's task. We need to give these pieces of information names so that we can use them, just like we do with variables. After we define our parameters, we use curly brackets to encase the code we want our function to run. Kind of like a neat little code package, where instead of using a ribbon, we wrap it in curly braces.
Let's take the example of making a salad. To make a salad, you need a few ingredients (parameters). Perhaps we're making a salad with tomatoes, lettuce and potatoes. We need to add all these ingredients to the bowl so we can mix it all in to one delicious salad. This is similar to function arguments. The function to make a salad needs the ingredients in order to make the salad.
function makeSalad(🍅, 🥬, 🥔){
  // steps to make salad
}
Parameters vs arguments
So far, the defintion of function parameters and arguments probably sound similar, so let's just clear it up a little here. As stated above, parameters are the names given to the information we will pass to the function. The arguments are the actual values that get passed to the function when it is invoked. This will probably become clearer once we start passing data, so stick around.
When does a function run?
The code inside a function is run when the function is "called" or "invoked". One way we can do this is through an event handler. An event is an action a user takes, for example, clicking a button, and so an event handler is code that is executed when an event occurs. Let's see some examples.
Here we have a button where if you click on it, you will see an alert pop up. We do this by adding the onClick attribute to the button, and passing the function definition to it.
A HTML attribute is information we add to the opening tag of a HTML element to control some of it's behaviour.
There are heaps of different events we can provide handlers for, such as onMouseOver and onBlur just to name a couple
Now that we've learned a little bit about functions, let's add them in to our ramen calculator. Here we can use a function to be called after we click on a button, to calculate whether Sam has successfully achieved her goal.
Sam's Expenses: 600
Budget: 800
Function arguments
Functions are great because they're specialised blocks of code that can be re-used, so we don't have to waste time writing the same thing over and over again. Let's take a look at the example below. Both Sam and Luannie have their own expenses. What if we want to check their statuses seperately? We already created a function above to calculate Sam's status, so why don't we just use that same one for Luannie as well? We could do something like this:
Budget: 800
Sam's Expenses: 600
Luannie's Expenses: 900
Can you see how our functions handleCalculateSamStatus and handleCalculateLuannieStatus are pretty much exactly the same, besides the fact one uses the samsExpenses variable, and the other uses the luanniesExpenses variable? Here is the perfect time to demonstrate how functions can be generalised and reused to minimise code.
The functions above are quite limiting that they can only calculate a specific person's status. What if we have more people? We don't want to have to create another almost-identical function to calculate their status. We just have to tweak our current one a little to make it perform a more generalised calculation. This generalisation means that instead of the function just calculating Sam's status, it will calculate any status, given it knows the person's expenses and budget. This can be done by passing arguments to our function. Basically, this just means passing pieces of data to our functions so they can be used for the calculation.
After the function name, we include brackets and add our arguments. Each argument is seperated by a comma. We can have zero, or heaps of arguments. The function then has access to these arguments in the exact same order they were passed.
The calculator below does the exact same thing as the previous example:
Budget: 800
Sam's Expenses: 600
Luannie's Expenses: 900
Look at how much more concise that is compared to the previous example! We just have one general function that can calculate the function for any person we need to add later on.
Parameters vs arguments revisited
Ok, now we've delved into function arguments a little bit, and we can properly distinguish them from parameters. Once again,parameters are the names given to the information we will pass to the function. The arguments are the actual values that get passed to the function when it is invoked.
// A Function with three parameters that makes a salad
function makeSalad(🍅, 🥬, 🥔){
  // steps to make salad
  return 🥗;
}

// The makeSalad function invoked with two arguments passed to it
makeSalad(🍅, 🥬);
So there is our salad example again. Just because the function has three parameters, doesn't mean we can't pass only two arguments. In this example, we don't have potatoes, just tomatoes and lettuce, so our salad will not have any potatoes.
Functions to return values
Functions can also return values. Sometimes it can be useful to have your function return a piece of information to use for something else. Let's take the example below. Both Sam and Luannie have expenses and a budget. Let's say instead of clicking a button to show their status, we just show it on the calculator. We can write concise code by creating a single function to do the calculations for the status generally, and then use it for both Sam and Luannie. This can be done by using the return keyword, followed by parenthesis and the value we want to return inside them. We can return all kinds of data types, not just strings.
Budget: 800

Sam's Expenses: 600
Sam's status: Success! 🎉

Luannie's Expenses: 900
Luannie's status: Not a success :(
Remember our makeSalad function from before? Well now that we've learned about functions returning values, let's add that into our salad function. We take the tomatoes, lettuce and potatoes as arguments, and after making the salad, we return it so it can be eaten! How delicious!
function makeSalad(🍅, 🥬, 🥔){
  // steps to make salad
  return 🥗;
}
Lesson summary
Congrats you've made it to the end of the lesson on JavaScript functions 🎉

A function is a block of code that performs a specific task.
We define our parameters inside the brackets which are names for the values that will be passed in and used by the function.
The values passed into our function are called arguments.
We've added our first button with an even handler onClick that calls a function.
We created a function that returns a value using the keyword return.
To do: Next lesson on variables (continued)
Next tutorial