Calling Functions
To run a function, you call it: write its name followed by parentheses and a semicolon:
function sayHello() {
console.log("Hello!");
console.log("Have a nice day!");
}
sayHello();This prints:
Hello!
Have a nice day!When JavaScript gets to a call, it jumps into the function, runs its body from top to bottom and then continues with the line after the call. You can call a function as many times as you like:
function sayHello() {
console.log("Hello!");
}
console.log("Start");
sayHello();
sayHello();
console.log("End");This prints:
Start
Hello!
Hello!
EndAt first, the program goes past the definition: JavaScript only remembers the function. Then it prints Start, runs the body of the function twice and finally prints End.
It's good practice to define functions first and call them below their definitions. Whoever reads the program then gets to know a function before they see it used.
Watch out for two common mistakes:
- Forgetting the parentheses.
sayHello;doesn't call the function, it only mentions it, so nothing happens, not even an error. Printing a function without the parentheses,console.log(sayHello), doesn't call it either. It only prints[Function: sayHello]. - A different name. The name in the call must be exactly the same as in the definition, including uppercase and lowercase letters, so
sayhello();ends with the errorReferenceError: sayhello is not defined.
Instructions
Below the function, call firstFunction three times.
Add a second line to the body of the function: console.log("Functions are great!");. Run the program: each of the three calls now prints both lines. You changed the code in one place, and all three calls do something new. That's what functions are for.