Here is a sample CodeSandbox for you to fork and use throughout the lesson â Lesson 12 CodeSandbox Starter: Functions
Warm-Up
Choose one application or website that you like to use.
Click through the application as you normally would while using it. Tally the number of times the application DOES something (examples: load content, respond to a click by showing a different screen or new content, etc.)
To build a web application, developers write LOTS of functions. Every time you click a button and see something happened, a function (or many functions) just performed its job. Every time you see new data load (your account page, someone elseâs profile page, detail of an image, etc.), a function just performed its job.
As we start learning about functions today, we wonât be writing ones quite as involved as some that are powering your favorite apps - but we will get the foundations!
What is a function?
A function is an action in our code. It has a specific job, and it sits around waiting to be asked to do it. It can perform its job as many or as few times as we need. It can have a very small job (add two numbers together) or a very big job (find the standard deviation of 1 million numbers). We write them, so we have control over what each function does!
In our class example today, we will write instructions for a robot to walk a dog.
Declaring & Calling a Function
Declare a Function
In order for our function (an action that we want to perform) to be sitting around, waiting to be called into action, that function needs to exist! We create functions by declaring them - giving them a name, and some instructions or directions to perform when called upon.
Hereâs what a very basic function declaration looks like:
function walkDog() { // code goes here }
We start with the keywordÂ
function, then name our function whatever we want. The name should describe the type of action our function is taking. Like variables, we use camelCase.Directly after the function name, we see open and close parentheses, then open and close curly brackets. The directions we want our function to take will live inside the curly braces. We can give a function as many directions as weâd like!
Letâs add some of the steps our robot needs to take to walk a dog. For now, we will useÂ
console.log()Â to print out the steps, so we know when our function is working.function walkDog() { console.log("Put on leash"); console.log("Put treats in pocket"); console.log("Put poop bag in pocket"); }
Now, this code alone wonât do anything. We have declared the function - told it what its job is. But we havenât called the function - or told it to carry out its task.
Call a Function
We have a nice function written, but we need to call it for the function to actually run. The great thing about functions is you can decide when they do their job. Maybe we only want a particular function to run when a user interacts with our site in a specific way. This puts us in complete control.
function walkDog() { console.log("Put on leash"); console.log("Put treats in pocket"); console.log("Put poop bag in pocket"); } walkDog();
The last line of the code snippet is what calls the function. Once we run the code, we should see each step print out on the right-hand side of the Sandbox.
Try-It | Declaring & Calling a Function
Declare and call a function namedÂ
sayHello. Write 2-4 console.log statements in it, saying whatever you'd like. Verify that it is running successfully by checking the console for the sentences.Declare and call a function namedÂ
sayGoodbye. Write 2-4 console.log statements in it, saying whatever you'd like. Verify that it is running successfully by checking the console for the sentences.Click here for Medium Practice đ¶đ¶
Did your
sayHello sentences print before or after your sayGoodbye sentences? Why?Arguments and Parameters
If we are really going to have this robot help out, we need it to be a little âsmarter.â We need it to know that if there are two dogs, it needs to put two leashes on, bring two poops bags, etc.
We can make functions a little âsmarterâ with something called arguments and parameters. Check out the code below, and then weâll talk about whatâs happening:
function walkDog(numberOfDogs) { console.log(`Put on ${numberOfDogs} leashes`); console.log(`Put ${numberOfDogs} treats in pocket`); console.log(`Put ${numberOfDogs} poop bags in pocket`); } walkDog(2); //=>Put on 2 leashes //=>Put 2 treats in pocket //=>Put 2 poop bags in pocket walkDog(7); //=>Put on 7 leashes //=>Put 7 treats in pocket //=>Put 7 poop bags in pocket
To allow our functions to be more dynamic or work in more situations, we can write the declaration with parameters. The parameter(s) live inside the parenthesis right after the function name. If there are more than one, they should be separated by a comma and a space.
When we call the function, it will now be expecting an argument. The argument is the value(s) you want to store to the parameter variable(s).
In our example above,Â
walkDog(2) was called with 2 passed in as an argument. So, the parameter numberOfDogs is now a variable that holds the value of 2. Anytime numberOfDogs is referenced inside of this function for this specific time itâs being run, 2 will be the value it uses.Below,Â
walkDog(7) was called. Anytime numberOfDogs is referenced inside of this function for this specific time itâs being run, 7 will be the value it uses.Using Parameters Like Variables
We can also do some calculations with our parameters - just like weâve done with variables. Letâs say we want to set an expectation that the robot walks each dog for 15 minutes. We can use the parameter to tailor the total number of minutes walked for each walk.
function timeToWalk(numberOfDogs) { var totalMinutes = numberOfDogs * 15; console.log(`You should walk a total of ${totalMinutes} minutes.`); }
However, parameters only operate like variables within a function. If you try to use a parameter name outside of the function, it will be like that parameter doesnât even exist.
Â
Try-It | Arguments and Parameters
In your CodeSandbox from earlier, write a function that will take 1 argument when called, a number. The function should
console.log the sum of that number and 5. Make sure to name your function something related to its job.Click here for a Medium Challenge đ¶đ¶
Write a function that will take 2 arguments when called, both being numbers, and that will
console.log the sum of those two numbers. Make sure to name your function something related to its job.Click here for a Spicy Challenge đ¶đ¶đ¶
Write a function that will take 3 arguments when called, all being numbers. It should sum the first two numbers, then multiply that sum by the third number and
console.log the result. Make sure to name your function something related to its job.Return Values
Up until now, inside our functions, weâve only calledÂ
console.log on values - in the future, we will need our functions to return values so we can use them elsewhere. This may not completely make sense now, but in the next couple lessons, all the pieces will tie together. Itâs good to get some exposure to it today.function timeToWalk(numberOfDogs) { var totalMinutes = numberOfDogs * 15; return totalMinutes; }
In this function, we are not callingÂ
console.log, so when we call it, we wonât see an output. But, we can store the output in another variable.function timeToWalk(numberOfDogs) { var totalMinutes = numberOfDogs * 15; return totalMinutes; } var minutes = timeToWalk(3); console.log(`You should walk a total of ${minutes} minutes.`); //=> You should walk a total of 45 minutes.
A couple of things to know aboutÂ
return:- Each function can only return one value
- If we donât explicitly return a value with the return keyword, the default return value isÂ
undefined
- Once the program reads theÂ
return keyword and the rest of the code on that line, it will exit that function. So, no code written below theÂreturn keyword will ever be read.
Discuss: Declaring & Calling a Function
Read through each line of the code below. With as much technical vocabulary as possible, explain what is happening at each line. Write this down in your journal.
function timeToWalk(numberOfDogs) { var totalMinutes = numberOfDogs * 15; return totalMinutes; } var minutes = timeToWalk(3); console.log(`You should walk a total of ${minutes} minutes.`); //=> You should walk a total of 3 minutes.
Takeaways
function timeToWalk(numberOfDogs) {Â declares the function
var totalMinutes = numberOfDogs * 15;Â declares a new variable that store the result of 15 multiplied by the number passed into the function
return totalMinutes; returns the value of theÂtotalMinutes variable
var minutes = timeToWalk(3); calls the functionÂtimeToWalk and passes in 3 as the argument. The return value of that is stored in the new variableÂminutes
Incorporating Conditionals
If we were only walking 1 dog, the sentences would read incorrectly, for example, âput on 1 leashesâ. Letâs write a conditional inside the function; if theÂ
numberOfDogs passed in is 1, we will print out one set of directions, and if it is greater than 1, we will print out another set.function walkDog(numberOfDogs) { if (numberOfDogs === 1) { console.log(`Put on ${numberOfDogs} leash`); console.log(`Put ${numberOfDogs} treat in pocket`); console.log(`Put ${numberOfDogs} poop bag in pocket`); } else { console.log(`Put on ${numberOfDogs} leashes`); console.log(`Put ${numberOfDogs} treats in pocket`); console.log(`Put ${numberOfDogs} poop bags in pocket`); } }
Try-It | Logic Inside a Function
Write a function that takes one argument, aÂ
gradeLevel. It should then print out "You are in elementary school" or "You are in middle school", etc. based on the grade level passed in.Now, write another function that takes in a number, aÂ
dogAge, and multiplies it by 7. It should print out a sentence telling the dog how old it is in human years.Functions
Over the course of camp, we will write a lot of functions! They will have different jobs, and some will look quite different from ours today, but youâve got a great foundation. Get a little more practice by completing the task below:
Practice: Functions: Building Your Own Calculator (JS only)
Open a new CodeSandbox. Create a set of functions for the following problems:
- A function called
addthat takes two numbers as arguments and returns their sum.
- A function called
subtractthat takes two numbers as arguments and returns the result of subtracting the second number from the first.
- A function called
multiplythat takes two numbers as arguments and returns their product.
- A function called
dividethat takes two numbers as arguments and returns the result of dividing the first number by the second.
đ¶Â Mild Challenge
Extend the calculator above by adding a
calculateArea and calculatePerimeter function that takes in the sides of a rectangle and outputs the area and perimeter.đ¶đ¶Â Moderate Challenge
Write a tip calculator function that takes in the total bill amount and calculates the 20% tip for the service received. The function should return the total amount to pay, including the tip. For example, if the bill is $100, the function should return $120.
đ¶đ¶đ¶Â Spicy Challenge
Write a tip calculator function that takes in the total bill amount and the quality of service received, and returns three different tip amounts and total amounts to pay based on the following criteria:
- If the service was excellent, tip 25% and return the total amount to pay including the tip.
- If the service was good, tip 20% and return the total amount to pay including the tip.
- If the service was poor, tip 10% and return the total amount to pay including the tip.
Â
Great job on learning functions! Take a few minutes to share your progress with a neighbor!
Â
For a summary of this lesson, check out the 12. JavaScript: Functions & The DOM One-Pager!