Functions: naming and reusing behaviour · Lesson 15 of 77 · concept
Declaring and calling your first function
About 45 minutes.
By the end of this lesson you can
- Say in your own words what a function is and why a program would want one.
- Write a function declaration and call it by name.
- Explain the difference between defining a function and calling it.
- Predict what a call produces when the function only prints and hands nothing back.
- Explain why a function declaration can be called on a line above the one that declares it.
What a function actually is
Explanation
Everything you have written so far runs the moment the program reaches it. Line 1, then line 2, then line 3, top to bottom, once each. That is fine for a program that does one thing once. It falls apart the moment you want the same three lines to happen in four different places, because the only tool you have so far is copying them and pasting them again.
A function is the fix. It is a set of steps that you write down once, give a name to, and — this is the part that matters — that do NOT run when the program reaches them. They sit there, named and ready, until somewhere else in the program you say the name and ask for them. Writing them down is one event. Running them is a completely separate event that can happen zero times, once, or two hundred times.
Hold on to that separation. Almost every confusing thing about functions comes from mixing up those two moments. When you are reading a function's body, nothing is happening yet: you are reading instructions, not results.
The recipe card
An analogy
Think of a recipe card for pancakes. Writing the card is not cooking. You can write it out, pin it to the fridge and go to bed, and no pancakes appear. The card is a set of steps with a name at the top — Pancakes — waiting for somebody to follow it.
Following the card is cooking. Someone picks it up, does what it says, and pancakes come out. They can follow it again tomorrow and again next week, and each time is a fresh run of the same written steps. Nobody rewrites the card each morning.
In JavaScript, writing the card is called declaring a function. Following it is called calling the function. The rest of this lesson is the notation for those two things, and nothing more.
The notation: declare, then call
Explanation
A function declaration is four things in a row: the keyword function, the name you are giving it, a pair of round brackets, and a pair of curly braces holding the steps. The steps inside the braces are called the function body. Everything inside those braces is the recipe; none of it happens yet.
Calling it is much shorter: write the name, then a pair of round brackets. Those brackets are the whole instruction. They mean do it now. The name on its own, with no brackets, is just the name — it refers to the function without running it, the same way saying the word pancakes does not make breakfast.
Function names follow the same rules as any other name in JavaScript, and the convention is to use a verb: greet, printBanner, calculateTotal. If you cannot think of a verb for it, that is usually a sign the function is trying to do more than one thing.
Why this is worth the extra typing
Why it matters
The obvious win is not repeating yourself. Four copies of the same three lines means four places to change when the requirement changes, and the bug is always in the copy you forgot.
The bigger win is the name. Once a chunk of behaviour is called calculateDeliveryFee, the code that uses it reads as a list of intentions instead of a wall of arithmetic. You can follow what a program is trying to do without holding every detail in your head at once, and that is the difference between code you can work on and code you can only stare at.
The third win is that a bug now has one home. When delivery fees come out wrong, there is exactly one function to open. That single property is what makes a program of ten thousand lines possible at all.
Why a call can appear above the declaration
A mental model
Before your program runs, JavaScript reads through it and sets up every function declaration it finds in that scope. By the time the first line actually executes, all of those names already refer to their functions. The visible effect is that a function declaration can be called from a line above the one that declares it. The official name for this is hoisting.
A usable mental model: the engine does a quick pass to collect the recipe cards and pin them all to the fridge, and only then starts cooking from the top of the list. This is true of function declarations specifically — the form that starts with the keyword function. There are other ways to make a function, and lesson four shows one that does not behave this way at all.
Do not read hoisting as permission to scatter declarations at random. Most code still reads better with a deliberate order. It is worth knowing because otherwise perfectly correct code can look impossible.
The three mistakes everyone makes first
A common mistake
Forgetting the brackets. Writing greet; instead of greet(); is not an error, and that is what makes it nasty. JavaScript evaluates the name, gets the function, and throws it away. Nothing prints, nothing breaks, and there is no message anywhere. If a function seems not to run, check for the brackets before you check anything else.
Expecting a printed value to be usable. A function that only calls console.log has put characters on the screen for a human to read; it has not handed anything back to the code that called it. Those are two different acts with two different notations, and the second one is the whole subject of lesson three.
Declaring inside something else by accident. If a declaration ends up inside another function's braces, the name only exists inside those braces, and calling it from outside is a ReferenceError. Lesson five gives that rule its proper name — scope — but the symptom is worth recognising now.
Recap
Recap
A function declaration writes down named steps without running them. A call — the name followed by round brackets — runs them. The two are separate events, and the same declaration can be called any number of times. Declarations are hoisted, so a call may appear above the declaration it uses. A function that only prints hands nothing back to its caller, which is the gap lesson three fills.
Worked examples
Every output below was produced by actually running the code in the same sandbox your exercises run in — it is not a prediction.
Declaring a function and calling it twice
The smallest useful function there is. Watch the body get written once and run twice, and notice that both printed lines come from the two calls at the bottom — not from the declaration.
1function greet() {2 console.log("Hello!");3}4 5greet();6greet();- line 1
The declaration begins: the keyword function, the name greet, empty brackets because this function needs no information from its caller, then the opening brace.
- line 2
The body. Nothing here happens while the declaration is being read. It happens once per call.
- line 3
The closing brace ends the body. At this point greet exists and has run zero times.
- line 5
The first call. The brackets are the instruction: do it now. This produces the first line of output.
- line 6
The second call. The same body, a fresh run. One recipe, two dinners — this is the entire point of a function.
What it prints
Hello!Hello!
Defining is not running
Proof that the two moments really are separate. The declaration is written first, but its output appears last, because nothing inside the body runs until the call on the final line.
1function announce() {2 console.log("The function ran.");3}4 5console.log("Defined, but not called yet.");6console.log(typeof announce);7announce();- line 5
This runs before anything in the body, even though it is written after it.
- line 6
typeof announce reports "function": the name exists and holds a function. The function still has not run.
- line 7
Only now does the body execute, which is why its line of output comes last.
What it prints
Defined, but not called yet.functionThe function ran.
Calling before the declaration
Hoisting on one screen. The call on line 1 works even though the declaration sits below it, because function declarations are set up before the program starts running.
1sayReady();2 3function sayReady() {4 console.log("Ready.");5}- line 1
Not a mistake and not a quirk of this sandbox: a function declaration is available everywhere in its scope, including above itself.
- line 3
The declaration that the call on line 1 found. Only the form starting with the keyword function behaves this way; lesson four shows a form that does not.
What it prints
Ready.Check yourself
Not scored, not stored. Getting one wrong is the useful part.
A program contains a working function called refresh. Which line actually runs its body?
What does this program print? Look carefully at the line that mentions shout without brackets.
function shout() { console.log("HELLO");}console.log(typeof shout);shout;shout();
Why does calling a function declaration on a line above its declaration work?
Write it yourself
Exercise · intro · 3 tests
Print a three-line banner
Finish printBanner so that calling it prints a three-line banner. The three lines, in order, are three asterisks, then the word Novus, then three asterisks again. Each line comes from its own console.log call. Do not print anything else — the tests compare the printed lines exactly, character for character.
printBanner takes no arguments. Every call prints exactly three lines: "***", then "Novus", then "***", in that order. It prints and nothing more, so a call to it produces undefined. Calling it twice prints the banner twice.
Define printBanner at the top level of your code — the tests call it by name.
Worth remembering
- What is the difference between greet and greet() ?
greet evaluates the name and gives you the function itself, running nothing. greet() calls it: the round brackets are the instruction to run the body now.
- Why can a function declaration be called on a line above the one that declares it?
Function declarations are set up before the code in that scope starts running, so the name already refers to the function when the first line executes. This is called hoisting.
Check this lesson against the source
We wrote the explanation; we did not invent the facts. This is the page that backs them.
MDN — function declaration (JavaScript reference)
Check there: The Description section states that function declarations are hoisted to the top of their scope, so a declared function can be called before the line that declares it.
MDN — Functions (JavaScript Guide)
Check there: The guide's overview of defining and calling functions.
Prefer to read the source in a structured breakdown? Turn this doc into a breakdown