JavaScript: Functions
Functions are a core concept of most programming and scripting languages, and are essentially just pieces of code which have been assigned a name. These pieces of code, once assigned a name, can then be executed or "called" via their name. Sometimes functions take values to do their job, for example a function might add the two numbers you give it together, these values are called parameters, but sometimes they don't require any values to function. We've used functions in the past, for example the alert
function which simply outputs the value passed to it in a pop-up box, however in this tutorial we'll be talking about how to actually create functions of our very own.
Firstly, let's focus on functions which don't take any values. These can be created by using the function
keyword, followed by the function name (which should be unique), followed by some empty brackets (if we had any parameters, we'd utilise the brackets here), and then finally followed by some curly brackets containing the function's actual code. So something like the following:
1 2 3 4 |
|
Note that some people prefer putting the first curly bracket on the same line as function WhateverNameHere()
, however it's all about personal formatting preference (I don't like it up there).
To create a functional example, let's just create a function which uses alert
to make a basic pop-up box when called:
1 2 3 4 |
|
Whenever we wanted to alert
"Howdy there!" later in our script after this function declaration (which usually takes place at the top of a script), we could call the function by simply writing its name followed by some empty brackets and a semicolon (as you've probably figured out by now, the brackets here are also empty because our function doesn't take any parameters).
Functions are very useful for creating preset routines which can easily be run through, and in a script structure can be good for making different parts of your script modular and separate (which is generally considered a very good thing). Functions also enforce the basic DRY guideline of Object Orientated Programming: Don't Repeat Yourself.
If you've been creating little scripts as this series has gone on, making use of the different features and quirks that you've learnt then you can probably already see how functions could be useful and could avoid a lot of repetition in code. If you're making a basic game in JavaScript for example, you might want to create a basic function routine for displaying the user inventory (and inside of this routine you might then make use of various structures like loops and if-statements).
In many function use-cases, however, it makes sense for the function to get values when called. A basic example might be creating a function which adds two numbers together. The first step to creating something like this is specifying some variables which function as parameters in the function declaration brackets (separated by commas) - in the example of adding two numbers we might want a variable called "one", and a variable called "two":
1 2 3 4 |
|
When we call the function, we then have to specify values for "one" and "two" in the brackets (also separated by commas) - so if we wanted to call the function with '5' and '10', we might write: AddTwoNumbers(5, 10);
.
The main query from here would then be to how we actually get the function to do the addition. Firstly, before you read on, try having a go to see if you can do it yourself without any further help (if you can, well done, if not, don't worry, just read on).
When we're working in the function's code, we can access whatever values have been passed to the function by using the names of the parameters - so when in the function's code segment, "one" will refer to whatever value was passed first, and "two" will refer to whatever value was passed second. This is where the topic of variable scope comes in as these variables are only accessible within the function's code, however that isn't something we're going to talk about much in this tutorial.
So using the above logic, we can add the two numbers by simply using the +
operator -- so one + two
or two + one
. The first way to get our function to actually do this in a noticeable way, would be to get it to use something like alert
:
1 2 3 4 |
|
This would work fine, but then what would we do if we wanted to prepend something to this after calculation but before output? And isn't the name "AddTwoNumbers" now slightly misleading since it actually outputs the addition and doesn't just add them?
Well we can get the function to "return" a value if we want. Writing return
followed by the value you want to return and then a semicolon means that wherever the function is called, the value that the function returned will essentially be in its place. So if our "AddTwoNumbers" function returned the addition of the two numbers, we could put the function call in a variable assignment or if-statement and it would work just as if we were adding the numbers right there. For example:
1 2 3 4 5 6 7 |
|
Notice how nesting functions in this way works perfectly fine! return
is extremely useful and provides a way to have feedback from the function without showing anything to the user -- it is common practice in some situations in which the function doesn't really need to return a value, to have functions return "true" if it completed its job with no issues, and "false" otherwise - this then allows the function call to be used within an if-statement to check if everything was successful.
If you want a challenge just to tie this tutorial off, try creating some functions of your own. It might be a nice idea to attempt to create a function which loops through an array, and maybe even try out the whole "true" or "false" thing to see how it works out for you!