Line At A Time
Lesson 23: Functions
Functions Write your own function and call it twice.
1function wave() {
2 console.log("Hello!");
3 console.log("How are you?");
4}
5
6wave();
7wave();
Terminal
$ node main.js
Hello!
How are you?
Hello!
How are you?
Every line, explained
function wave() {
function defines a function: your own named block of code. Defining it does nothing on its own: it waits until somebody calls it by name.
console.log("Hello!");
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Part of the wave function's body.
console.log("How are you?");
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Also part of the body: the function prints two lines every time it runs.
}
This } closes the function.
wave();
Writing the function's name with round brackets calls it: JavaScript jumps up into wave, runs its body, then comes back here.
wave();
Calling it again runs the body again. Write once, use as many times as you like. That is the whole point of functions!