The flow for each individual topic should be as follows:
- Discuss high level overview: why it matters, how it fits in to overall goals, why we're learning it in this order
- Explain logic via pseudo-code, either on whiteboard or projector.
- Live code example as a group
- Individual exercises
- Group exercise (pick one of the more challenging individual exercises, go through it together — can be student driven if someone volunteers)
- Review last week's material: instructors go around the room individually and check in with students, make note of recurring questions. Pose quick, popcorn-style questions on topics from last week: verbal, whiteboard, code on the projector. Go over answers together.
- High level discussion of functions: what they are, how to use them.
- Discuss named vs anonymous functions.
- Using parameters
- Statement blocks
- Callbacks
- Discuss homework
- if statement
- switch statement
- for loop
- while loop
A function is effectively a container holding a set of instructions. Sometimes functions are anonymous, and only meant to be used once, but more often than not we give them names to be referenced at a later point in our program. A good function is generic, meaning it uses placeholder variables (called parameters) so that it can be called multiple times with different data.
Take, for instance, a sum function:
function sum(a,b){
return a + b;
}
This function uses two parameters, a and b, to serve as placeholders until the function is called with real data passed in. Once this function is defined, we can call it as many times as we'd like with any arbitrary data:
sum(8,2);
sum('hello', 'world');
sum([1,2,3],[4,5,6]);
There may be many times in a program where we are adding two pieces of data together, so rather than writing that same line "return a + b" over and over again, we can define a function sum(a,b) once, and use it repeatedly.
A libraries like jQuery is basically a big collection of functions. It does quite a bit more than that, but one of the big value-adds is its extensive set of pre-written functions. When we define named functions in our JavaScript programs, we are effectively building a small "library" for our reference.
Using functions is a two-step process: declaring them and calling them. When we delcare (or define) a function, we create our block of instructions. When we later go to call them is when the program actually executes that set of instructions.
A function declaration is made up of three required pieces and one optional one:
- The reserved word function
- The name you decide to give it
- (Optional) placeholder parameters
- Block of code to execute (the instructions)
What is a reserved word? JavaScript, along with other languages, has a list of words that cannot be used as names for variables, functions, or parameters — as they have dedicated uses built into the language. One of those is function, and that's the one we're concerned with today.
So a function declaration starts with the reserved word function, followed by a name of your choice, then two parentheses (optionally filled with one or more parameters), then a block of executable code between two curly braces:
// This function takes in a name as a paremeter, and says hello to that name
function hello(name) {
alert('Hi ' + name);
}
We now have a named function hello that takes in a name as a parameter, and alerts the message "Hi [name]". The important thing to remember here is that name is simply a placeholder that we will replace when we call the function later on. The placeholder is needed in order to properly set the instructions. This way, when actual data is passed in (e.g. "Hillary" or "Jim"), the function knows where to put that data and what to do with it.
So now we've declared a function, let's see how to actually use it!
The second step of using a function is to call it. Calling an existing function is a little bit like updating an existing variable, in that we drop the reserved word in front. So to call our function hello that we declared above, we can just refer to it by its name (omitting the word function).
hello("Jamie");
What we've done here is call the function hello, and pass in the string "Jamie" as a parameter. What the computer does next is basic substitution. Where our original function delcaration used the placeholder name:
function hello(name) {
alert('Hi ' + name);
}
the computer will now replace the parameter name with whatever we passed in, in this case the string "Jamie". Our parameter gets inserted into the code block between the curly braces, and is subsituted in wherever name was previously referenced. So the resulting code will be:
alert('Hi ' + "Jamie");
which will result in a popup alert saying "Hi Jamie".
Everything inside the curly braces {} of a function declaration is an executable code block. Blocks can include everything we've covered in the previous two classes: variables, if statements, switch statements, for loops, while loops, etc.
These are the procedural instructions the computer will follow when the function is called.
Let's create a function that expands a bit on the hello function defined in the previous section:
function greeting(name, case){
if (case == "hello"){
var _message = "Hi" + name + ", how are you today?";
else{
var _message = "Bye" + name + ", nice seeing you!";
}
alert(_message);
}
greeting("Tom", "hello");
Here we've written a function that takes in two parameters: a name (just like the original function) and a type of greeting. The executable code block contains a conditional statement that will create a different message depending on the value passed in for the case parameter. If the greeting is "hello", the message will say "Hi [name], how are you today?". Otherwise, it will say "Bye [name], nice seeing you!". This function is not perfect, as we could pass in something other than "hello" or "goodbye", so maybe an else if would be smart to add:
function greeting(name, case){
if (case == "hello"){
var _message = "Hi" + name + ", how are you today?";
else if (case == "goodbye"){
var _message = "Bye" + name + ", nice seeing you!";
}
else {
var _message = "That's not a greeting I'm familiar with!";
}
alert(_message);
}
Now, if something other than "hello" or "goodbye" is passed in, our function is equipped to handle it.
Code blocks can get much more complex, but at their root they serve the same purpose: executable instructions to be followed when the function is called.
A very common practice is to call another function within the code block of a function. This technique is called a callback, and is often used to call a function once certain conditions have been set (variables updated, data received, etc). An example usecase might be a printSum function. Imagine we want to set variables, then add them together, and then print the result. Our new printSum function can use the sum function that we've already written:
function printSum(){
var num1 = 8;
var num2 = 7;
alert(sum(num1,num2));
}
function sum(a,b){
return a + b;
}
the sum function here is a callback. sum is called within the alert function, and its result is passed back via the return statement. Without including return there, the message alerted would be "undefined", as the sum function would not be set up to return a value.
Callbacks will become increasingly useful as we begin to write more complicated programs, particularly with AJAX — where we will need to wait for data to be completely received before executing functions that use it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
http://javascript.info/tutorial/arguments
Using the documents provided here, write a program that takes in a password input (via clicking on a virtual keypad) and checks to see if it is correct (when compared with one we set in our JS file). If it is correct, redirect the user to a congratulatory page, otherwise alert them that the password entered was incorrect.
Provided in the documents is an HTML file, a CSS file (neither of which you need to modify), an answer.js file (which contains a correct solution to the assignment, for you to reference if you're stuck), and a problem.js file (which contains guided instructions and empty space for you to fill in your own solutions.