By the end of this lesson, you should be able to do the following:
- Understand what a function is and why we use functions.
- Declare and define a function as a block of code.
- Understand how to pass input to a function.
- Understand how to store the output of a function.
- Understand the purpose of the return keyword.
- Execute a function.
We can now start to group the code we're working with into "functions" and use functions to write more realistic, complex programs. Let's explore how functions work.
A function is a collection of lines of code, also known as a "block" of code. We run that code when we write the appropriate statement to "execute" the function. A function is a type of "control flow", meaning function definitions in our code may not execute sequentially through the code file. For example, we may define a function at the top of our file, but only execute that function at the bottom of our file.
We can think of functions as "recipes" of code; a fixed set of instructions or steps, that can take in a variable input (e.g. number of dinner guests) and give a certain output (enough food for dinner), even though the instructions are statically defined. Functions have 3 key parts:
- Input(s)
- Pre-defined operations on the input
- Output
Functions sometimes do not take in input, and sometimes do not return an output, but for now we will work with this basic structure.
Functions are necessary to abstract complexity away from the main logic of our applications. This allows us to break problems down into ever-smaller sub-problems, simplifying the process of coding complex applications. In this module we will see 2 use-cases of functions.
- Purpose-built data manipulators that take inputs and give outputs. These are sometimes called "helper" functions. We will define our functions' inputs and outputs, and all the instructions for that function will be contained in a block of code as part of the function definition.
- Logic sequences that we wish to encapsulate in a "sub-routine". We do this with our
main
function.main
contains everything we want to happen when the user clicks Submit. It is common for sub-routine functions to rely on several other helper functions.
Define a function that "abstracts" the km-to-miles conversion we did in 2.3: Our First Program.
- Start at the top of
script.js
- Create a variable for our function:
var convertKmToMiles
. Note that function variable names start with a verb, by convention, to distinguish them from variables storing other data types. With few exceptions such as themain
function, function names should almost always start with a verb. - Assign a function definition to that variable:
var convertKmToMiles = function () {}
{% hint style="info" %}
Note the beginning and end of the function "block" with curly braces ({}
). We will add function logic within these curly braces. Semicolons marked the end of a line of code, curly braces are used to mark the start and end of a code block.
{% endhint %}
var convertKmToMiles = function () {};
Define what logic happens when the function is executed. In our case, we want to convert KM to miles.
var distanceInMiles = distanceInKm * 0.62;
Use the return
keyword to define the function's output value. For our convertKmToMiles
function, our return value is the distance in miles.
{% hint style="info" %}
Note that the output of a function may not be the output of the overall program, because functions can call other functions. The output of the overall Coding Basics starter code program is the return value of the main
function.
{% endhint %}
return distanceInMiles;
We define and name a function "input parameter" as distanceInKm
. Functions can have 0 or more input parameters.
var convertKmToMiles = function (distanceInKm) {
All together our function looks like the following.
var convertKmToMiles = function (distanceInKm) {
var distanceInMiles = distanceInKm * 0.62;
return distanceInMiles;
};
The syntax to run a function is to code the function name followed by parentheses (()
). Without parentheses, the function is just a variable whose value is a function, and the function's logic will not run.
convertKmToMiles();
Input parameters go within the function execution parentheses. Our convertKmToMiles
function expects 1 input parameter, a distance in KM. For our function to work, we must pass this parameter to our function by specifying the parameter in the parentheses.
var myKmDistance = 4;
convertKmToMiles(myKmDistance);
Let's test this function on its own outside of the Coding Basics starter code.
- Open Chrome Developer Tools by selecting View > Developer > JavaScript Console from the Chrome menu bar
- Paste the code from the last code snippet above into the console and hit
Enter
- Observe the calculated result
- Type the function name into the console and hit
Enter
. You should see the code block you defined. - Run the function from the console again with a different input value
convertKmToMiles(7676);
Create several variables and use them as input to your function.
var kmsToHome = 4;
var kmsToSchool = 6;
var kmsToWork = 7;
Use these variables as input to our function. Paste each function call into the console and hit Enter
one by one.
convertKmToMiles(kmsToHome);
convertKmToMiles(kmsToSchool);
convertKmToMiles(kmsToWork);
We can see the result of our calculation in the console and capture that value for later. Paste this code into the console:
var result = convertKmToMiles(7676);
Type in the name of the variable, result
, and press Enter
to see the given value.
Back in script.js
, Call convertKmToMiles
from our main
function, providing input
as a parameter to convertKmToMiles
.
var convertKmToMiles = function (distanceInKm) {
var distanceInMiles = distanceInKm * 0.62;
return distanceInMiles;
};
var main = function (input) {
var myOutputValue = convertKmToMiles(input);
return myOutputValue;
};
We can now better understand the main
function in our starter code. You may have noticed we currently do not execute main
from script.js
. Our starter code runs main
for us whenever we click the Submit button. The code for this mechanism is inside index.html
. We will not yet explain in detail how exactly the input from the box is linked to the main function in script.js
, but we will learn that in Module 6.
- The
input
parameter ofmain
is what the user types in the input box - The
return
value ofmain
is what gets displayed in the output box
With this in mind, assign the value of input
to myOutputValue
to see this connection. Then change the code again to assign the string value "wow hello" to myOutputValue
.
- Duplicate and run the code from this module
- Paste the other function examples in instead of
convertKmToMiles
- Remove the
return
statements from the examples. What happens and why? What does thereturn
statement do and how does it work? - Remove the
distanceInKm
parameter from the function definition. What happens and why? Replace the parameter afterward. - Change the variable name
distanceInKm
to another name everywhere. What happens and why? Change the name back todistanceInKm
afterward.
Two trains are leaving to Tokyo. Train 1 is traveling 200kph, and will reach Tokyo in 2 hours. Train 2 is newer and can travel faster, but is delayed due to a signalling fault.
Build a program for Train 2's conductor to calculate how fast Train 2 needs to travel to arrive at Tokyo at the same time as Train 1, based on how long it was delayed. Output the speed in kph. (Ref Solution)
A user can enter the number of minutes past 1pm and the app will calculate the angle between the hour and minute hand. You are free to decide how else your clock will work: if the minute hand moves in 5 minute increments or moves every second, etc.