Functions
What is a function?
A function is a group of instructions that you can execute at a later time.
function someNameHere() {
// Do something
// then do something else
}
// adding the () at the end is what instructs the computer to execute the
// function
someNameHere(); // this will run the function
You name it with the keyword function
.
Arguments
You can pass in arguments
which help make the function reusable.
function add(a,b) {
a+b; // will result in 8 when add(5,3) is called
}
add(5,3);
Return
keyword
Functions usually have a return
keyword at the end. Without it, the function
won’t return any value.
function add(a,b) {
return a+b; // will return the result of the expression (in this case "5+3")
}
var result = add(5,3); // without the "return" keyword above, the value of
// "result" would be "undefined"
Passing a function as an argument (listeners)
Ocasionally you’ll need to pass a function to another function. Event listeners
are a common example for this.
// el is an element on the page we've defined earlier
// when I click on the element, the function named "someFunction" will be
// executed
el.addEventListener('click', someFunction);
// DON'T DO THIS. INCORRECT.
el.addEventListener('click', someFunction());
// this will run with the RESULT of someFunction because of the ()
// -> el.addEventListener('click', 10);
function someFunction() {
return 5+5;
}
Exercises. Now you try it.
1)
Create a function named subtract.
// 1. create a function named subtract
// 2. call the function
// 3. Ensure it returns 5
function someName() {
}