JavaScript functions: reusable blocks of code
Write JavaScript functions with parameters and return values, use default values and arrow functions, understand scope, and split a program into small, testable pieces.
🎯 By the end of this lesson you will be able to:
- Define and call functions with parameters
- Return values from functions and use the results
- Write arrow functions and explain variable scope
Outline
What you'll learn and why it matters
As programs grow, you find yourself writing the same steps again and again: work out a price with tax, format a date, check a form field. A function gives a name to a set of steps so you can run them whenever you need, with different inputs. Functions are also how you respond to clicks and key presses in lesson 9.
Defining and calling a function
function greet(name) {
console.log(`Hello, ${name}! Welcome to the café.`);
}
greet("Asha");
greet("Kofi");Console (Chrome and Edge)
Hello, Asha! Welcome to the café. Hello, Kofi! Welcome to the café.
| Part | Here | Meaning |
|---|---|---|
| Keyword | function | Starts a function definition |
| Name | greet | What you call it by; a verb is a good choice |
| Parameter | name | A variable that receives the value passed in |
| Body | { … } | The steps that run each time it is called |
| Call | greet("Asha") | Runs the function; "Asha" is the argument |
Defining a function does nothing on its own. The steps run only when you call it, with brackets.
Returning a value
Most useful functions return an answer so the rest of the program can use it:
function lineTotal(price, quantity) {
const subtotal = price * quantity;
return subtotal * 1.05;
}
const chai = lineTotal(40, 3);
const bread = lineTotal(60, 1);
console.log(chai);
console.log(bread);
console.log(`Order total: ${chai + bread}`);Console (Chrome and Edge)
126 63 Order total: 189
return does two things: it sends a value back, and it ends the function immediately. Any lines after a return in the same block do not run.
function showDouble(n) {
console.log(n * 2);
}
function double(n) {
return n * 2;
}
const a = showDouble(5);
const b = double(5);
console.log(a);
console.log(b);Console (Chrome and Edge)
10 undefined 10
Default values
function priceWithTax(price, taxPercent = 5) {
return price + (price * taxPercent) / 100;
}
console.log(priceWithTax(200));
console.log(priceWithTax(200, 18));Console (Chrome and Edge)
210 236
If the caller leaves out an argument, the parameter uses its default. Without a default, a missing argument is undefined, which often leads to NaN.
Arrow functions
Arrow functions are a shorter way to write a function and are very common in modern JavaScript, especially for small jobs like the array methods in lesson 7 and event handlers in lesson 9.
const square = (n) => n * n;
const describe = (name, age) => {
const group = age < 18 ? "junior" : "adult";
return `${name} (${group})`;
};
console.log(square(7));
console.log(describe("Ravi", 15));Console (Chrome and Edge)
49 Ravi (junior)
| Form | Example | Note |
|---|---|---|
| Function declaration | function square(n) { return n * n; } | Can be called from anywhere in the file |
| Arrow, one expression | const square = (n) => n * n; | The value after => is returned automatically |
| Arrow, with a body | const f = (n) => { … return …; }; | With braces you must write return yourself |
Scope: where variables can be seen
Variables created with let or const inside a function (or any { } block) exist only inside it. This is called scope, and it stops functions accidentally changing each other's variables.
function makeTea() {
const cups = 2;
console.log(`Making ${cups} cups`);
}
makeTea();
console.log(cups);Console (Chrome and Edge)
Making 2 cups
The console shows this error
Uncaught ReferenceError: cups is not defined
Practice
Guided exercise
Temperature converter
Write a function toFahrenheit(celsius) that returns the temperature in Fahrenheit (multiply by 9, divide by 5, add 32). Print the result for 0, 37 and 100.
- Define
function toFahrenheit(celsius) { … }. - Return
celsius * 9 / 5 + 32. - Call it three times inside
console.log, using a template literal for a clear message.
Show the solution
function toFahrenheit(celsius) {
return celsius * 9 / 5 + 32;
}
console.log(`0°C = ${toFahrenheit(0)}°F`);
console.log(`37°C = ${toFahrenheit(37)}°F`);
console.log(`100°C = ${toFahrenheit(100)}°F`);Console (Chrome and Edge)
0°C = 32°F 37°C = 98.6°F 100°C = 212°F
How to get there: The function does one job and returns the answer, so the same code works for any temperature. Each call's result is placed straight into the message.
Your turn
Initials
Write an arrow function initials that takes a first and last name and returns their capitalised first letters, like initials("meera", "iyer") → "MI". Print the result for two names.
Show the solution
const initials = (first, last) => (first[0] + last[0]).toUpperCase();
console.log(initials("meera", "iyer"));
console.log(initials("kofi", "mensah"));Console (Chrome and Edge)
MI KM
How to get there: A string can be read by index like an array, so first[0] is its first letter. The one-expression arrow function returns the joined, upper-case letters automatically.
Common mistakes
Forgetting the brackets when calling
You see: Nothing happens, or the console shows the function's code
Fix: Call with brackets: greet(), greet("Asha").
Using console.log instead of return
You see: The result is undefined when you try to use it
Fix: Return the value, then log it where you call the function.
Writing code after return
You see: Those lines never run
Fix: Put everything the function must do before return.
Using a function's inner variable outside it
You see: ReferenceError: … is not defined
Fix: Return the value and store it in a variable outside.
Forgetting return in an arrow function with braces
You see: The function returns undefined
Fix: With { } you must write return; without braces it is automatic.
Recap
- A function names a set of steps; it runs only when called with brackets.
- Parameters receive values;
returnsends a result back and ends the function. - Defaults fill in missing arguments; arrow functions are a short form.
- Variables declared inside a block stay in that block's scope.
Key terms
- Function
- A named, reusable block of code.
- Parameter and argument
- A parameter is the variable in the definition; an argument is the value passed in a call.
- Return value
- The value a function sends back to the code that called it.
- Scope
- The part of a program where a variable can be used.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. What does `add(2, 3)` return? function add(a, b) { console.log(a + b); }
2. What does `const triple = (n) => n * 3; triple(4)` give?
3. With `function hi(name = "friend")`, what does `hi()` use for name?
4. A variable is declared with const inside a function. Where can it be used?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.