35 min·beginner

Lesson 3

Function declarations

Build a practical mental model for function declarations and use it in working JavaScript.

By the end, you will be able to…

  • Explain function declarations in your own words
  • Use function declarations in a small program
  • Recognize and debug a common failure mode

Build the mental model

A function packages a transformation you can name, reuse, and test in isolation. function declarations are hoisted, meaning they can be called before their definition appears in the file.

main()
calculateOrder()
applyTax()

Newest call on top · pops off when it returns

The call stack

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: 16

Why this matters

Naming a transformation ('square', 'formatPrice') makes the calling code read like a sentence, and lets you fix a bug in one place instead of many.

Real-world example

Every reusable formatting or validation rule in a real app — currency formatting, email validation — lives in a small named function like this.

Common mistakes

  • Copy-pasting logic instead of extracting a function
  • Giving functions vague names like doStuff()
  • Forgetting the return statement and getting undefined back

Try it yourself

Challenge

Write a cube(n) function and log cube(3).

Practice

Knowledge check

What does it mean that function declarations are hoisted?

Summary

Extract repeated or nameable logic into a function so it can be reused, tested, and read clearly.