Reusable blocks of code that take inputs and give answers
When you need the same steps in many places, you don't have to copy them. Put them in a function once, give it a name, and call that name whenever you need it.
flag
What you'll learn
How to put code in a function and run it whenever you need it.
How to give a function inputs with parameters.
How to get an answer back with return.
waving_handWelcome to functions
A function is a named block of code. Writing it is called declaring it, and running it is called calling it.
You've already called functions made by others: console.log( ) and document.getElementById( ). Now you'll make your own.
A function can take inputs, do its job, and give back an output.
blender
Think of a blender at a fruit shake stand. You put in fruit (the input), press the button (call the function), and a shake comes out (the output).
The blender works the same way every time, whether you put in mango or banana. You don't need to know how its blades turn. You only need its name and what to put in.
nutritionPut in mangoesWhat you give the machine."mango"parameter: fruit
arrow_forward
blenderThe blenderDoes the same job every time you press the button.function makeShake(fruit) { }makeShake("mango")
arrow_forward
local_cafeGet a mango shakeWhat the machine gives back.return fruit + " shake";
Now let's see the code ↓
nutritionPut in mangoesWhat you give the machine."mango"parameter: fruit
arrow_forward
blenderThe blenderDoes the same job every time you press the button.function makeShake(fruit) { }makeShake("mango")
arrow_forward
local_cafeGet a mango shakeWhat the machine gives back.return fruit + " shake";
The input goes in through the parentheses, and return sends the output back.
searchA closer look
How a function is written
functionkeyword
addPricesname
(a, b)parameters (the inputs)
{ return a + b; }body (the job)
Function names follow the same rules as variable names. A name that starts with a verb, like addPrices or showGreeting, tells you what the function does.
Parameters and arguments
Parameters are the names in the declaration, like a and b. Arguments are the real values you pass when you call it, like 25 and 40.
They match up in order, so inside the function, a is 25 and b is 40.
return: the answer
return sends a value back to the line that called the function. You can keep it in a variable, log it, or use it in a sentence.
return also ends the function right away, so any lines after it inside the function don't run.
Why use functions?
Functions save you from writing the same code twice. When something needs to change, you fix it in one place.
They also make code easier to read: a line like showGreeting("Ana") says what it does. In JS Lesson 8, you'll use functions to react to clicks and typing.
constructionLet's build it
Let's write a few small functions for Front Page Bytes. The HTML and CSS stay the same in every step: a heading and two boxes, #greeting and #total.
The first steps write to the console, and the last step changes the page.
1Step 1: Declare a function and call it
Your code
function sayHello() { console.log("Hello, reader!");}sayHello();sayHello();
Lines 1 to 3 declaresayHello. Nothing happens yet. Lines 5 and 6 call it, and each call runs the code inside, so the console shows Hello, reader! twice.
2Step 2: Give it an input
Your code
function sayHello(name) { console.log("Hello, " + name + "!");}sayHello("Ana");sayHello("Ben");
name is a parameter. The first call passes "Ana", so inside the function name is "Ana". The second call passes "Ben".
One function, two different messages.
3Step 3: Get an answer back with return
Your code
function addPrices(a, b) { return a + b;}const total = addPrices(25, 40);console.log(total);console.log(addPrices(100, 50));
For age 10, the if is true, so the function returns Please ask a parent first. and stops. Line 5 never runs.
For age 15, the if is false, so the function goes on to line 5 and returns Welcome!
5Step 5: Use functions on the page
Your code
function addPrices(a, b) { return a + b;}function showGreeting(name) { document.getElementById("greeting").innerHTML = "Good morning, " + name + "!";}showGreeting("Ana");document.getElementById("total").innerHTML = "Total: " + addPrices(25, 40) + " pesos";
showGreeting doesn't return anything. Its job is to change the page. addPrices returns a number, which the last line puts inside a sentence.
Both boxes now show the results: Good morning, Ana! and Total: 65 pesos.
sticky_note_2Quick notes
functionDeclare and call
function sayHello() { console.log("Hi!"); }
How to use
function name() { }Declares a function: a name for a block of code.
name();Calls it: runs the code inside. The () are needed.
Declaring a function doesn't run it. Only calling it does.
Examples
A message you show many times.
function welcome() { console.log("Welcome to the class!");}welcome();
Clear a box on the page.
function clearBox() { document.getElementById("box").innerHTML = "";}
( )Parameters and arguments
function sayHello(name) { } sayHello("Ana");
How to use
function name(a, b) { }a and b are parameters: names for the inputs.
name(5, 10);5 and 10 are arguments: the values you pass in.
They match up in order: a gets 5, b gets 10.
Examples
Greet anyone by name.
function greet(name) { console.log("Hi, " + name);}greet("Ana");
Two inputs.
function introduce(name, age) { console.log(name + " is " + age);}introduce("Ben", 12);
returnSend an answer back
return a + b;
How to use
return value;Sends a value back to where the function was called.
return also stops the function. Lines after it don't run.
Without return, a function gives back undefined.
Examples
Double a number.
function double(n) { return n * 2;}console.log(double(21));