Think of a function as having four parts.
- Declare the function using var, and then give it a name.
- Then you must use the function keyword to tell the computer that you are making a function.
- The bit in the parentheses is called theparameter. Think of it as a placeholder word that we give a specific value when we call the function. See the hint for more.
- Then write your block of reusable code between { }. Every line of code in this block must end with a ;.
Syntax
var functionName = function() { code code code; code code code; (more lines of code); };
Let's say you want to print a greeting each time a person walks past your desk. And you want to personalize that greeting with their name. Typing out:
console.log("Hello, Betty");
console.log("Hello, Laura");
and so on for each person will take forever!
- On line 11, call the greeting function and put in a name that you want the greeting function to include.
- Press Run and see the function get into action! Saves you so much time.
Hide hint
When we want to join together two strings, we put a plus sign.
console.log("Hey" + "you") will print out Heyyou. That's not what we want!
If you want a space between words, you must add that space as well!
console.log("Hey" + " " + "you") will print out Hey you
This joining of strings is calledconcatenation
//Below is the greeting function
//See line 7
//We can join strings together using the plus sign +
//See the hint for more details about how this
var greeting = function (name) {
console.log("Great to see you," + " " + name);
};
//On line 11, call the greeting function!
console.log("function" + " " + "Betsy")