EP31 – Functions in JavaScript

Functions in any programming language are almost as important as having variables. So that should go without saying that functions are hugely important to understand and to use in the JavaScript language.
Functions in JavaScript
Functions are what allow us to re-use code, and organize the functionality of our programs into neat little packages.

That’s really all they were created for. To organize the functionality of our code, and to allow us to re-use that code over and over again by “invoking” or “calling” the function.

So let’s start things off by asking the following question: “What do you mean by organizing the functionality of your code?”

The first thing I’ll point out is, look at the word “functionality”, isn’t it interesting that it contains the word “function”?

Oh snap!

By functionality, I mean the actions that our programs perform.

Let’s say we’re looking to create a number guessing game. The computer will pick a random number between 1 and 100, and we are tasked with guessing what number the computer has picked. We have 5 guesses, and each time we guess, the computer will tell us if we need to guess higher, or lower.

Okay, cool, so we have an idea of how this game should work, now how would we outline the “actions” that this program should perform? In other words, how do we outline the functions that will exist?

Well the way I would do it is I would think about all the steps that would need to happen in order to carry out this task in real life. It might look something like this:

  1. The computer will need to randomly pick a number between 1 and 100
  2. I would then hazard a guess at what number they picked, say, 50
  3. The computer would tell me if I am right, or if I need to guess higher, or lower
  4. I would then make my second attempt at guessing the number (let’s assume I needed to guess higher), so I would choose 75
  5. The computer would tell me if I am right, or if I need to guess higher, or lower
  6. I would then make my third attempt at guessing the number (let’s assume I needed to guess higher), so I would choose 85
  7. The computer would tell me if I am right, or if I need to guess higher, or lower
  8. This would repeat until I either guessed right, or I used up all my attempts

When you write out all of the steps, you can quickly see where some of the steps are similar based on how they repeat.

For example, I can see that the computer always needs to check if I was right, or if I need to guess higher, or lower. This is essentially an action that’s performed MANY times by the computer… so this would be a perfect candidate for a function.

The second thing that happens often, is that *I* would attempt to guess a number, so that could be a function as well.

And finally, there’s that bit at the beginning that only happens once, which is where the computer needs to pick a random number. What I would do here is just realize that this is something that happens when we START a game… or perhaps more specifically, something we do when we want to start a NEW game. So if we want to be able to play MANY games in a row, this could become a function as well, as we would need to invoke this many times.

So, we’ve outlined three functions, all we need to do is give them names.

That’s right, functions need names, it makes the code more “human readable”, which is a good thing 😉

Syntax for Functions in JavaScript

Let’s talk syntax.

If you’ve got a Java programming background, this syntax will look slightly different. There’s a specific reason why it’s different though, and that’s because JavaScript has dynamic types, so there’s no need to specify a type in the function.

Here’s a general outline of a function’s syntax in JavaScript:

function myFunction (param1, param2, param3)
{
  // insert relevant code here
}

In the example above you’ll notice that I have three parameters being “passed into” the function. This is just an example, and you can feel free to pass in ZERO parameters, or more.

The process of “passing parameters” into a function is very common in modern day programming languages. What’s happening here is that the function is saying “Hey, I need certain parameters to be given to me in order for me to do my job correctly.” If you don’t give a function what it wants, meaning, if you don’t pass it the right number of parameters (whether that’s none, one, two, three, or more) then the JavaScript engine will complain.

In the case of my generic example above, we have no concept of what the parameters mean or what they do, as it’s just a generic example.

Here’s an example of a generic function that doesn’t require any parameters:

function anotherFunction ()
{
  // insert relevant code here
}

Voila, another function that this time doesn’t require any parameters.

Alright let’s talk real world examples now…

Functions for the Number Guessing Game

Let’s break down what one of the functions would look like in our game. Let’s use the function that verifies if the user has correctly guessed the randomly selected number. Before we just into the code, we’ll need to make an assumption that somewhere above the code we’re about to see, there’s a variable that’s been declared that holds the number we wish to guess. Let’s call this variable numberToGuess.

Okay great, let’s see the function:

function isNumberHigherOrLower (usersGuessedNumber)
{
  if (usersGuessedNumber == numberToGuess)
  {
    return "Correct";
  }
  else if (usersGuessedNumber > numberToGuess)
  {
    return "Lower";
  }
  else
  {
    return "Higher";
  }
}

First thing to note here is that we’ve assigned a meaningful name to the function. I decided that I wanted to call this function isNumberHigherOrLower, to me this is a pretty good name because it more or less defines what the code inside the function will be doing. If I wanted to be even more verbose, I could have named it isGuessedNumberHigherOrLowerOrCorrect, but there comes a point where super long function names just get annoying.

I’ll let you decide what your threshold is for function name length!

The second thing to note is that I’m using the return keyword.

Returning Values from Functions

Functions can do one of two things:

  1. Functions can just execute code and then allow the flow of code to exit and return back to wherever the function was originally called
  2. Functions can return data to the place that called the function

This gives functions an added layer of usefulness, because not only can they allow you to re-use code and organize your code, but they can also give you relevant data based on the specific execution of the function.

So in the example of our function, a different value is returned based on what you pass in.

This means different INPUTS lead to different OUTPUTS.

Let’s assume the number to guess is 50, based on this assumption, take a look at what our function would return based on the inputs we give it:

isNumberHigherOrLower(49); // returns "Higher"
isNumberHigherOrLower(51); // returns "Lower"
isNumberHigherOrLower(50); // returns "Correct"

You see?

We get three different outputs from the function based on what number we input into the function.

So based on the outputs, we can have our game behave in different ways.

By the way, I also just showed you how to invoke/call a function. To tell your application that you want to “use” a function’s code, you just type in the function’s name followed by an open and close parenthesis… you should also pass in any values that it needs. In the case of our isNumberHigherOrLower function, it only wants one parameter, which we named usersGuessedNumber.

It can be a bit confusing if you’ve never seen a function in action before, but I assure you, you’ll become very comfortable with them after you’ve created a handful of JavaScript programs for yourself.

In Summary

JavaScript functions are very similar to Java functions with one major difference.

JavaScript functions don’t require you to put in the parameter variable’s type in the function’s definition, this is because JavaScript uses dynamic typing, so it wouldn’t make sense to put in a type for the parameter, right?

Functions are extremely useful and without them, all programming languages would be rendered pretty much useless.

So you need to learn them and master them.

If you don’t quite “get it” yet, you’ll be seeing plenty more examples of JavaScript functions in action in the coming tutorials.

And as always, don’t forget to put your email address into our handy dandy box below to receive a free googie delivered right to your inbox. I’m pretty sure you’re gonna want to check it out… I’m kind of a big deal 😉