JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 5: Functions and Reusable LogicLesson 21 of 150About 40 minutes

Lesson 21: Function declarations and expressions

01Opening question

The same tax calculation appears in five places in a shop's code. The tax rate changes. How many places must you edit?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Defining a function does not run it. Each greet() call runs the body once.

function greet() {
  console.log("Welcome to the shop!");
}

greet();
greet();

03Objective and prerequisites

Learning objective: Declare and call functions, write function expressions, explain hoisting of declarations, and name functions for what they do.

You need: Lesson 16: For loops, Lesson 20: Solving problems with iteration

Skills practised: Functions, Function declarations and expressions.

04Explanation

A function is a named block of code you can run whenever you need it. Write it once, call it many times.

A function declaration starts with function, a name, brackets and a body: function showMenu() { ... }. Defining it does nothing visible; calling it with showMenu() runs the body.

A function expression stores a function in a variable: const showMenu = function () { ... };. You call it the same way.

Name functions with verbs that say what they do: printReceipt, calculateTax, isValidEmail. Good names let the code read like a list of steps.

05Definitions

Function
A reusable block of code that runs when it is called.
Function declaration
A statement that defines a named function: function name() {}.
Function expression
A function created as a value, often stored in a variable.
Call (invoke)
Running a function by writing its name followed by brackets.
Hoisting
Function declarations are available before their line in the code.

Open the full glossary

06Visual learning object

Function call stack and return-value tracer. Step into and out of function calls and watch the call stack grow and shrink.

Loading the interactive object…

Open the full Function return-value visualizer page with its guided experiment.

07Examples

ex-021-01Declare once, call many times Browser-executable JavaScript

The body runs each time the function is called.

function printDivider() {
  console.log("----------");
}
console.log("Receipt");
printDivider();
console.log("Tea  $3");
printDivider();
Sample input
None
Expected output
Receipt ---------- Tea $3 ----------
Common mistake
Writing printDivider without brackets, which does not call it.
Try this
Change the divider to 20 = signs and see every place update.
Source
examples/ex-021-01-declare-and-call.js (repository pending publication)

ex-021-02A function expression Browser-executable JavaScript

A function can be stored in a const like any other value.

const showStatus = function () {
  console.log("Store open");
};
showStatus();
console.log(typeof showStatus);
Sample input
None
Expected output
Store open function
Common mistake
Forgetting the semicolon is usually fine, but forgetting () means the function never runs.
Try this
Store a second function and call both.
Source
examples/ex-021-02-function-expression.js (repository pending publication)

ex-021-03Declarations are hoisted Browser-executable JavaScript

A declaration can be called before the line that defines it.

welcome();
function welcome() {
  console.log("Hello from a hoisted function");
}
Sample input
None
Expected output
Hello from a hoisted function
Common mistake
Expecting the same with a const function expression, which throws a ReferenceError.
Try this
Change it to a const expression and read the error.
Source
examples/ex-021-03-hoisting.js (repository pending publication)

ex-021-04Functions are values Browser-executable JavaScript

Printing a function shows the function, not its result.

function today() {
  return "Monday";
}
console.log(today);
console.log(today());
Sample input
None
Expected output
[Function today] Monday
Common mistake
Logging the function instead of calling it.
Try this
Store today in another variable and call that.
Source
examples/ex-021-04-function-as-value.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Call the function

Recognise the difference between referencing and calling a function.

function openStore() {
  console.log("Doors open");
}
openStore;

Receipt header function

Move repeated code into a function.

console.log("==========");
console.log("CORNER CAFE");
console.log("==========");
console.log("Order 1: Latte");
console.log("==========");
console.log("CORNER CAFE");
console.log("==========");
console.log("Order 2: Mocha");

Store hours helpers

Write a declaration and an expression and use both.

const OPEN = "9:00";
const CLOSE = "17:00";

09Prediction

Commit to an answer first, then run the real code to compare.

function ping() {
  console.log("ping");
}
console.log("start");
ping();
ping();

What is printed, in order?

10Debugging investigation

The footer appears before the items

Receipts show the thank-you footer at the top instead of after the items.

function printFooter() {
  console.log("Thank you!");
}
function printItems() {
  printFooter();
  console.log("Tea");
  console.log("Cake");
}
printItems();

More cases in the Debugging Detective Laboratory

11Practical scenario

One place to change

A shop prints the same footer on receipts, emails and invoices. Moving it into one function means a new phone number is changed once and appears everywhere.

function printFooter() {
  console.log("Thanks for shopping!");
}
printFooter();

12Knowledge check

1. How many times is Hi printed?

function hi() { console.log("Hi"); }
hi();
hi();
  • 0
  • 1
  • 2
  • 3

2. What does defining a function do?

  • Runs it immediately
  • Stores it so it can be called later
  • Prints it
  • Deletes old code

3. Why is nothing printed?

function show() {
  console.log("Shown");
}
  • The function has no name
  • It is never called
  • console.log is wrong
  • Functions cannot print

4. Which can be called before its line in the code?

  • A function declaration
  • A const function expression
  • Both
  • Neither

5. What is printed?

const f = function () {};
console.log(typeof f);
  • function
  • string
  • undefined
  • object

6. Which function name is best?

  • doStuff
  • calculateTax
  • x
  • function1

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Call the function: Prints Doors open
  • Receipt header function: Output unchanged; printHeader is a function; Header text written once
  • Store hours helpers: Prints both lines; One declaration and one expression
  • ex-021-01: output matches the documented expected output
  • ex-021-02: output matches the documented expected output
  • ex-021-03: output matches the documented expected output
  • ex-021-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-05-functions-and-reusable-logic/lesson-021-function-declarations-and-expressions/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • A function is defined once and called many times.
  • Declarations: function name() {}. Expressions: const name = function () {}.
  • Calling needs brackets.
  • Declarations are hoisted; const expressions are not.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Functions
Context: I am new to functions.
Task: Explain defining versus calling with a receipt example.
Constraints: Beginner level.
Expected behaviour: I can explain why functions reduce repetition.
Testing: Give me three programs to refactor.
Code prediction Call order
Context: I know how to declare and call functions.
Task: Give me five programs and ask the order of their output lines.
Constraints: Wait for answers.
Expected behaviour: Include hoisting.
Testing: Explain any I miss.
Debugging Function does nothing
Context: My function prints nothing.
Task: Ask questions that lead me to the problem.
Constraints: No direct answer.
Expected behaviour: I fix it myself.
Testing: List the three most common causes.
Exercise generation Refactoring practice
Context: I finished the receipt header exercise.
Task: Create two programs with repeated code for me to turn into functions.
Constraints: Exact output must stay the same.
Expected behaviour: Each has at least two repeated blocks.
Testing: Include the expected output.
Code review Function names
Context: Here are my function names.
Task: Review them and suggest clearer verb-based names.
Constraints: Explain each suggestion.
Expected behaviour: Every name says what the function does.
Testing: Give me a naming checklist.