Unit 4 · Thinking like a programmer
Defining a function doesn’t run it
Writing function greet(name) { … } only stores the recipe. The steps run when the code calls it, such as greet("Sam"), and each call can pass a different value into name.
The mix-up
What people often think
“Writing a function runs it.”
What the tutor says
A definition is a recipe card. The steps only happen when the code calls it, for example greet("Sam").
Which line in this program would make greet actually run?
How it works
Parameters are empty boxes until a call fills them. name has no value when the function is defined; it gets "Sam" from the call greet("Sam").
In const message = greet("Sam"), the right side runs first. message only gets its value once greet has finished and returned.
An example
function greet(name) { // defined: nothing happens yet
return "Hi " + name;
}
const message = greet("Sam"); // called: runs nowClose cousins of this mix-up
The tutor watches for these in the same lesson.
“The input box is filled when the function is defined.”
name is empty until a call fills it. Each call can pass something different.
“message gets its value as soon as the line starts.”
The right side runs first. message only gets a value once greet has finished and returned.
Practise it with a tutor watching
Functions: machines with inputs and outputs
Define a function, call it with inputs, and return a value the rest of the code can use.
Free with an account. The first two units need no account.