JavaScript with Sean Doyle

Lesson 4: Functions

Functions

The Big 5 Concepts

  1. A function is a block of code that waits until it is called by name to execute.
  2. Functions can have parameters that act like variables within the function.
  3. Functions can return one value at the end of their logical operations.
  4. Functions can be used anywhere in our logic, and can be called from inside other functions.
  5. 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.