17.10.2020

Functions, Parameters and Return Values

Fundamentals of Programming Pt. 2

Functions, Parameters and Return Values

This is part 2 of our blog post series: Fundamentals of Programming.

In our previous blog post we showed you how variables work in JavaScript, what data types are, and how the different operators work.

In this blog post, we will have a look at functions. You will learn how you can build functions in JavaScript, how you can pass data to them and get data back.

Let’s dive right in! 🏊‍♀️

Let’s have a look at this example:

var age = 19;
 
// Can we have a soda?
if (age > 1) {
  console.log("Here you go!")
} else {
  console.log("Not old enough, sorry.")
}
 
// Can we have a beer?
if (age >= 18) {
  console.log("Here you go!")
} else {
  console.log("Not old enough, sorry.")
}
 
// Can we have wine?
if (age >= 18) {
  console.log("Here you go!")
} else {
  console.log("Not old enough, sorry.")
}
 
// Can we have wodka?
if (age >= 21) {
  console.log("Here you go!")
} else {
  console.log("Not old enough, sorry.")
}

You can always look up and run the examples of this blog post here. We would suggest that you create your own Repl at repl.it and do all the examples yourself. Learning by doing is the best method for learning to code.

You can see that we repeat a code snippet multiple times. These lines are repeated twice:

if (age >= 18) {
  console.log("Here you go!")
} else {
  console.log("Not old enough, sorry.")
}

and two other blocks are very similar.

We can actually put this repeated code snippet into a block. This block then gets a name, and we can use it wherever we need. This is called: a function.

Functions

If we take above example and put the duplicated code snippet into a function, it will look like this:

function canWeDrinkThis() {
  if (age >= 18) {
    console.log("Here you go!")
  } else {
    console.log("Not old enough, sorry.")
  }
}

The function keyword tells us: Here comes a function!
Then there’s the name of the function (canWeDrinkThis). You can name it however you like.
The name of the function is followed by an opening and closing bracket ().
And then the opening curly bracket { signals: here comes the code block! It ends with the closing curly bracket }, which signals that this is the end of the code block.
Inside the curly brackets goes the code snippet that the function is supposed to do.

Now this is only the “definition” of the function. We call it the function declaration.
What does this mean? It means that we just defined what the function is going to do.
In order to actually run the function, so that our code snippet is executed and does something, we need to call it:

canWeDrinkThis()

You call the function by using the function name and brackets (). This is the function call.

This is important to remember: You first declare the function, then you call it. It is important that you know the difference between function declaration and function call. If this is a bit confusing, hang on. It will get more clear with practice.

The function gets only executed when you call it. You can, in fact, call it multiple times, and it will get executed multiple times. Try it:

canWeDrinkThis()
canWeDrinkThis()
canWeDrinkThis()

What happens if you run this? It gets called three times, so you will have three console outputs.

This is a bit like creating a recipe: When we declare the function, it is like we write the recipe down on a sheet of paper. When we call the function, it is like we are actually cooking the dish of the recipe.

Now with recipes, there’s usually a list of ingredients at the beginning: the things that go into the meal that you are about to cook. Functions have a similar concept: parameters.

Function Parameters

A function parameter is data that goes into a function: the input of a function.

We also call function parameters params.

If you look at our first example you see: we have four blocks that are very similar. The only thing that changes is the age threshold for each beverage. We could make our function more flexible to take this into account, by using parameters. We can pass the minimum age for a beverage into the function as a parameter.

This would look like this:

function canWeDrinkThis(minAge) {
  if (age >= minAge) {
    console.log("Here you go!")
  } else {
    console.log("Not old enough, sorry.")
  }
}

Here, minAge is the minimum age that is allowed for a beverage. It is passed as a parameter.

For beer, for example, the minAge would be 18. We put that number inside the brackets () when we call the function:

canWeDrinkThis(18)

And similarly, we could call that function for the other beverages:

canWeDrinkThis(1)   // Soda
canWeDrinkThis(18)  // Beer
canWeDrinkThis(18)  // Wine
canWeDrinkThis(21)  // Wodka

Everything that starts with two slashes // is a comment, it is ignored and will not be executed.

So what is happening here? The function is getting called four times in a row, once for each beverage. The minimum age for the beverage is passed as a parameter: 1 for soda, 18 for beer, 18 for wine, and 21 for wodka. So we have 4 output messages, that should be something like this:

Here you go!
Here you go!
Here you go!
Not old enough, sorry.

It would be nice to see in the output what beverage it is, right? We can do that by passing the name of the beverage as parameter as well. We then use it in the console.log("...") text, like this:

function canWeDrinkThis(beverage, minAge) {
  if (age >= minAge) {
    console.log("Here you go! Have a " + beverage)
  } else {
    console.log("Not old enough for " + beverage + ", sorry.")
  }
}

What happens here is: we define an additional parameter called beverage.
This parameter is then treated as a variable in the block of the function.

If you don’t remember variables, check out the previous blog post where we covered them.

In the console.log statements, we use the variable beverage and put it into the output text.

As we learned above, this is just the function declaration. We also need to call it. Let’s call the function once for each beverage:

canWeDrinkThis("Soda", 1)
canWeDrinkThis("Beer", 18)
canWeDrinkThis("Wine", 18)
canWeDrinkThis("Wodka", 21)

This should give an output like this:

Here you go! Have a Soda
Here you go! Have a Beer
Here you go! Have a Wine
Not old enough for Wodka, sorry.

We now have one console log for each output with the beverage name.

Parameter Data Types

As you remember from our previous blog post, variables have data types, e.g. integer (number) or string (text). The same is true for parameters. Parameters are just like variables that are put into functions.

In the function call

canWeDrinkThis("Beer", 18)

you can see that we pass parameters of different data types: First, the beverage name – as a string. Second, the minimum age for the beverage – as an integer.

In the function declaration you need to be a bit conscious about the data type, because you don’t see it. It just shows the parameter name:

function canWeDrinkThis(beverage, minAge) { ...

Therefore you need to keep in mind how you use the parameter in the code of the function.

In our case, beverage is used later in the code as a string:

  console.log("Here you go! Have a " + beverage)

And minAge is used as an integer:

  if (age >= minAge) { ...

So we need to make sure that when we call the function, we pass the right data type at the right place. In this case: first a string, then an integer.

canWeDrinkThis("Beer", 18)

This is nothing to worry about, you just need to be careful that you pass the right data types into the function at the right place.

Return Values

Functions can have a return value. What does that mean?
It means we can make a function return something. In other words, we can get an output from the function.

Look at this example:

function isOldEnough(age, minAge) {
  var oldEnough = age >= minAge;
  return oldEnough;
}

This function returns true or false, because it has a return value:

return oldEnough;

Here, oldEnough is the variable that we created one line before. With return, we give it back: we say that the output of the function should be whatever oldEnough is (true or false).

So if we call the function, we get a value back, and can, for example, save this value in a variable:

var canDrink = isOldEnough(19, 18);

isOldEnough(19, 18) is the function call – we call our new function here with the parameters age (19) and minAge (18).

Then we save it in a variable: var canDrink.

You can print it on the console to see the value:

console.log(canDrink)

This should print true in the console.

You can play around with it, change the numbers that you pass into the function, and see how the result changes.

Putting it all together

Let’s wrap up what we learned so far and apply everything to the first example of this article.

First, we are going to write down our function declarations. We will need 2 functions:

  • isOldEnough(age, minAge) that returns true or false
  • canWeDrinkThis(beverage, minAge) that makes our console output

So here they go:

// Function declarations

function isOldEnough(age, minAge) {
  var oldEnough = age >= minAge
  return oldEnough
}

function canWeDrinkThis(beverage, minAge) {
  var oldEnough = isOldEnough(age, minAge)
  if (oldEnough) {
    console.log("Here you go! Have a " + beverage)
  } else {
    console.log("Not old enough for " + beverage + ", sorry.")
  }
}

You see here that I am already calling the function isOldEnough() in the function canWeDrinkThis(). And yes, of course you can make a function call inside a function declaration. This is common practice and it is how you use functions, basically.

Now there are two lines of code that we could make even shorter:

// ...
  var oldEnough = isOldEnough(age, minAge)
  if (oldEnough) {
// ...

This would be the same as writing:

// ...
  if (isOldEnough(age, minAge)) {
// ...

You see what I did here? I skipped creating a new variable oldEnough, and used the function directly in its place in the if (...) brackets. We replaced the variable with the function call.

This is possible, because the function has a return value. We know the return type of our function is true or false, so if we put this in the if (...) clause, this works.

Note: If the function would return something different, like a string or an integer, we couldn’t use it in the if (...) clause.

This means: If the function has a return type, I can treat a function call just the same way as a variable. This is suitable if I call it only once and don’t need to save the value for re-usage. In our case, it makes the function one line shorter. And shorter is always better. 😊

So we call the function isOldEnough() now in our other function canWeDrinkThis(), but one important thing is missing: we also need to call the function canWeDrinkThis().
We want to do this once for each beverage:

// Function calls

var age = 19;

// Can we have a soda?
canWeDrinkThis("Soda", 1)
// Can we have a beer?
canWeDrinkThis("Beer", 18)
// Can we have wine?
canWeDrinkThis("Wine", 18)
// Can we have wodka?
canWeDrinkThis("Wodka", 21)

This is giving you the output you want:

Here you go! Have a Soda
Here you go! Have a Beer
Here you go! Have a Wine
Not old enough for Wodka, sorry.

As a summary, here is what the whole program should look like now:

// Function declarations

function isOldEnough(age, minAge) {
  var oldEnough = age >= minAge
  return oldEnough
}

function canWeDrinkThis(beverage, minAge) {
  if (isOldEnough(age, minAge)) {
    console.log("Here you go! Have a " + beverage)
  } else {
    console.log("Not old enough for " + beverage + ", sorry.")
  }
}

// Function calls

var age = 19;

// Can we have a soda?
canWeDrinkThis("Soda", 1)
// Can we have a beer?
canWeDrinkThis("Beer", 18)
// Can we have wine?
canWeDrinkThis("Wine", 18)
// Can we have wodka?
canWeDrinkThis("Wodka", 21)

Nice, isn’t it? 😊 Much shorter and no unnecessary code duplication anymore! ✨

You can look up the solution code here. Feel free to run it and play around with it.

 


 

Well done! If you followed the tutorial, you should be able to write functions, tell a function declaration from a function call, pass parameters to functions, and let a function return a value.

This is not easy. If you have the feeling that you didn’t quite get 100% of it, stay patient. Play around with the functions you have, and get some practice. Everything will get more clear and easy with practice.

As an exercise, you can make the function canWeDrinkThis(...) return true or false and print it on the console. You can look up the solution for this exercise in our Repl here.

We hope this tutorial helped you understand functions. Were you able to follow? If yes, share it with a friend who also wants to learn coding. And if not, drop me a line and ask your question. Thanks for reading, and happy coding! 👩‍💻

back to overview