JavaScript with Sean Doyle
Lesson 4:
Functions
Functions
The Big 5 Concepts
- A function is a block of code that waits until it is called by name to execute.
- Functions can have parameters that act like variables within the function.
- Functions can return one value at the end of their logical operations.
- Functions can be used anywhere in our logic, and can be called from inside other functions.
- Variables declared inside a function cannot be “seen” outside of that function. Where a variable can be seen is referred to as its “scope”.
Code Samples
//Creating a function...
function doThis() {
//Code to complete this particular task
}
//Calling a function (by its name)...
doThis();
//A function with parameters...
function doThis(one, two) {
var z = one + two;
alert(z);
}
//Calling the function - it needs 2 things to do its job.
doThis(8, 12);
//Functions can return one thing.
function doThis(one, two) {
var z = one + two;
return z; //Note the keyword 'return'
}
//We create a variable to hold the value returned by the function.
var functionResult = doThis(3, 4);//functionResult will be holding 7.
For More Information
A Deeper Dive