“Boil the water, put in the noodles, wait 3 minutes, dissolve the soup.” Because these steps have the name “make ramen,” we can ask for them with the single phrase “make ramen.” You can do the same thing in programming. Giving a name to a set of steps—that’s a function.
Let’s write it
function greet() {
console.log("Hi, I'm Shima!");
}
greet();
greet();The console shows the greeting twice.
| Part | Meaning |
|---|---|
function | The signal for “I’m making a set of instructions” |
greet | The name given to the instructions |
Inside { } | The content of the steps |
greet() | The call that runs the instructions |
You can pass ingredients: arguments
If you pass ingredients into the ( ) when you call, you can use them inside the steps. These ingredients are called arguments.
function greet(name) {
console.log("Hi, " + name + "!");
}
greet("Shima");
greet("Chick");It’s the same set of instructions, yet the results differ: “Hi, Shima!” and “Hi, Chick!” One set of steps, results that change depending on the ingredients—this is the moment functions get a lot more useful.
You can return a result: return
You can also return a computed result to the caller. That’s return.
function double(number) {
return number * 2;
}
let answer = double(5);
console.log(answer);double(5) transforms into the result 10, which is stored in answer. Picture it as “a machine where you put in an ingredient and out comes a processed result.”
Arguments aren’t limited to one. Separate them with commas and you can pass as many ingredients as you like.
function add(a, b) {
return a + b;
}
console.log(add(3, 4));It receives two ingredients, a and b, and returns the result of adding them. When you call, you pass two in the same order: add(3, 4).
Actually, you’re already using them
Reading this far, did you notice a shape that looks familiar? On Shima’s page, in script.js, you wrote code like this.
form.addEventListener("submit", function (event) {
event.preventDefault();
thanks.textContent = thanksMessage;
});This function (event) { ... } is exactly a function. You made it right there without giving it a name and handed it to addEventListener, saying “when submit happens, run these instructions” (since it has no name, it’s called an anonymous function). (event) is an argument, holding the detailed information about the event that happened. That’s why you were able to write event.preventDefault().
Summary of this lesson
- A function = a named set of instructions. Two stages: making it (
function) and calling it (name()) - You can pass arguments (ingredients) with
( ), and return a result withreturn - The
function (event)on Shima’s page is a function too (a nameless anonymous function)