By the end of this lesson, you will be able to:
:information_source: Definition: A function is a block of code that can be called whenever you need it. Think of it as a recipe that you can use over and over again!
This is the syntax for a basic function:
function functionName() \{
// statements to run
\}
Here is an example of how we would use a function:
function addTwoNumbers(x, y) \{
return x + y;
\}
There are a few parts to this function, so let's break it down:
The code inside the function actually will not run until it is called.
Once we declared a function, let's run the code by calling it:
addTwoNumbers()
addTwoNumbers(3,4)
Can you see what would happen when we call the function in console.log? Let's call the function:
console.log( addTwoNumbers(3,4) );
function addTwoNumbers(x, y) \{
return x + y;
\}
Browser Console (F12):
7
As you can see the browser console (F12) outputs the value 7. The return value states that it is the addition of x and y:
Usually developers will place functions at the last part of the code for code-readability.
Another interesting feature of a function is the ability to return value to the caller.
Assuming that we want to find the area of one face of a cube.
Note:
- A cube is made from squares.
- All edges have the same length.
function area(edge)\{
return edge * edge;
\}
This function will accept the length of edge as argument and returns the area.
We can have a prompt to receive user input and let the function do its job:
var userInput = prompt("What is the length of edge of your cube?");
console.log("Area: " + area(userInput));
What happens:
Output in console:
// If you put in 5 after web page prompts you
Area: 25
Generally, a return value is used where the function is an intermediate step in some kind of calculation.
For example, you want to get to a final result that involves some values that need to be calculated by a function before getting the final result. After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation.
Example:
var userInput = prompt("What is the length of edge of your cube?");
console.log("Area: " + area(userInput));
console.log("Total Surface Area: " + totalSurfaceArea(userInput));
function area(edge) \{
return edge * edge;
\}
function totalSurfaceArea(edge) \{
//There are 6 faces in total for a cube
return area(edge) * 6;
\}
Output in console:
// If you put in 5 after web page prompts you
Area: 25
Total Surface Area: 150
In function totalSurfaceArea, the function area is the intermediate step of its calculation.
A function will immediately stop at the point where the return statement is executed.
Example:
console.log(brushTeeth());
function brushTeeth()\{
console.log("Put 1cm toothpaste");
return "Stop! Why am I putting shampoo on the toothbrush?"
console.log("Brush for 3 minutes");
console.log("Rinse the mouth");
\}
Output in console:
Put 1cm toothpaste
Stop! Why am I putting shampoo on the toothbrush?
Knowing the return can stop the function half way, we can make use of it to terminate the function if the condition meets.
Example:
var userInput = prompt("What is the length of side of your cube?");
console.log("Area: " + area(userInput));
console.log("Total Surface Area: " + totalSurfaceArea(userInput));
function area(edge) \{
if (edge < 0) \{
return "Cannot be calculated";
\}
return edge * edge;
\}
function totalSurfaceArea(edge) \{
//There are 6 surfaces for a cube
if (edge < 0) \{
return "Cannot be calculated";
\}
return area(edge) * 6;
\}
Output in console:
// If you put in 5 after web page prompts you
Area: 25
Total Surface Area: 150
// If you put in -5 after web page prompts you
Area: Cannot be calculated
Total Surface Area: Cannot be calculated
Anonymous function is a function without a function name.
One common use for anonymous functions is as arguments to other functions.
setTimeout(arg1, arg2)
We have the function setTimeout which is a predefined function in JavaScript.
This function accepts 2 arguments:
We can pass the anonymous function as an argument for function setTimeout:
setTimeout(function () \{
console.log('Execute later after 3 seconds');
\}, 3000);
The example above will print out the string in the console after 3 seconds.
Output in console:
// You will see the output after 3 seconds
Execute later after 3 seconds
Another alternative is:
setTimeout(print, 3000);
function print() \{
console.log('Execute later after 3 seconds');
\}
Although this alternative brings you exactly the same result, very often developers do the anonymous function syntax to complete their task as they can save the time of thinking the function name on a more important task.