Code You Can Call by Name

You have been calling functions since your first program: console.log, Number, Math.floor. A function is a named piece of code that you can run whenever you need it. Now you will write your own:

function greet(name) {
  console.log(`Welcome, ${name}!`);
}

greet("Alice");
greet("Bob");

Output:

Welcome, Alice!
Welcome, Bob!

A function definition has four parts: the word function, a name, a list of parameters in parentheses, and a body in curly braces. A parameter is a variable that gets a new value each time the function is called. The value you pass in a call is called an argument. So greet("Alice") runs the body with name set to "Alice". When the body finishes, the program goes back to the line after the call. The same function with a different argument gives a different result.

Defining a function does not run it. Only a call runs the body. Also, JavaScript reads all function definitions before it runs the file. This is called hoisting, and it means you can call a function on a line above its definition:

greet("Emma");

function greet(name) {
  console.log(`Welcome, ${name}!`);
}

Output:

Welcome, Emma!

This works, but most programmers still put the definitions first and the calls after them. Code is easier to read in that order.

Why write functions at all? A good name tells the reader what happens. greet(visitor) is clear even if you never read the body. Functions also save you from repeating code. If the same lines appear in three places and you find a bug, you must fix it three times. With a function, you fix it once. When you notice that you are copying lines you already wrote, put them in a function.

Two naming habits are worth learning now. Write names in camelCase, and start them with a verb, because functions do things: sendReport, printTotal. And give each function one clear job.

In the exercise, the calls are already written. Write the greet function that they call.