Functions: Reusable Blocks of Code
Define functions with parameters and return values, write arrow functions, and understand scope so variables live exactly where they should.
Welcome back!
Step 1 of 13Learn
Write it once, use it everywhere
Suppose your store page converts prices to include 8% sales tax in six different places. You copy the formula six times. Then the tax rate changes, you update five of the six, and one page now shows the wrong price. Functions prevent this: you write the logic once, give it a name, and call it wherever you need it.
function withTax(price) {
return price * 1.08;
}
console.log(withTax(100)); // 108
console.log(withTax(25)); // 27The anatomy:
functionkeyword, then the name (withTax).- Parameters in parentheses (
price): placeholders for the inputs. - The body in curly braces: the code that runs.
returnsends a value back to whoever called the function, and ends the function immediately.
When you call withTax(100), the value 100 is the argument; inside the function, price holds 100 for that call.
A function without a return statement returns undefined. This is the single most common beginner bug with functions: the function calculates the right answer, logs it, and then the caller receives undefined because the result was never returned. Logging is not returning. console.log shows a value to you; return hands it to the rest of the program.
Step 2 of 13Practice · Diagram
Anatomy of a function
In withTax(100), which part receives the value 100?
Tap the shape that answers the question, then press Check.
- function withTax(price) { ... }
Full code: function withTax(price) { return price * 1.08; }
- function keyword
Tells JavaScript a function definition starts here.
- Name: withTax
How you call it later. Verbs or verb phrases read best.
- Parameter: price
A placeholder that receives the input value.
- Body { ... }
The code that runs on every call.
- return
Sends a value back to the caller and ends the function.
- Call: withTax(100)
100 is the argument; the call evaluates to 108.
Step 3 of 13Practice · Choose one
What does this code print?
``js
function double(n) {
console.log(n * 2);
}
const result = double(4);
console.log(result);
``
Step 4 of 13Learn
Parameters, defaults and multiple inputs
Functions can take several parameters, separated by commas, and arguments are matched by position:
function rectangleArea(width, height) {
return width * height;
}
rectangleArea(4, 3); // 12If you pass fewer arguments than parameters, the missing ones are undefined, and 4 * undefined is NaN. A default value protects against that:
function greet(name = "friend") {
return `Hello, ${name}!`;
}
greet("Sam"); // "Hello, Sam!"
greet(); // "Hello, friend!"Functions can call other functions, which lets you build big tasks from small, testable pieces:
function subtotal(price, qty) { return price * qty; }
function total(price, qty) { return withTax(subtotal(price, qty)); }Good functions do one thing and have a name that says what: calculateTotal, isValidEmail, formatDate. A function named doStuff that is 80 lines long is a sign it should be split. Names starting with is, has or can conventionally return booleans.
Step 5 of 13Practice · Code challenge
Write a function average(a, b, c) that returns the average of three numbers.
average(2, 4, 6)average(10, 0, 5)average(1, 2, 2)
Step 6 of 13Learn
Arrow functions and functions as values
Modern JavaScript has a shorter syntax, the arrow function:
const withTax = (price) => price * 1.08;
const add = (a, b) => a + b;
const sayHi = () => "Hi!";When the body is a single expression, the value is returned automatically, with no return keyword and no braces. With braces, you need return again:
const withTax = (price) => {
const rate = 1.08;
return price * rate;
};With exactly one parameter, the parentheses are optional: n => n * 2.
In JavaScript, functions are values, just like numbers and strings. You can store them in variables, put them in arrays, and pass them to other functions. A function passed to another function is called a callback:
setTimeout(() => console.log("Two seconds later"), 2000);Here the arrow function is handed to setTimeout, which calls it after 2,000 milliseconds. Callbacks are everywhere in JavaScript: in array methods, event handlers and network requests, all of which you will meet later in this course.
Step 7 of 13Practice · Match the pairs
Match each arrow function to the value it returns when called with 5.
Tap an answer, then tap the place where it belongs (or drag it there).
- n => n * 2
- n => n % 2 === 0
- n =>
#${n} - n => { n + 1; }
Step 8 of 13Learn
Scope: where variables live
A variable declared with let or const exists only inside the block (the pair of curly braces) where it was declared. This is block scope.
const siteName = "ShopCo"; // global: visible everywhere
function checkout(total) {
const tax = total * 0.08; // local to checkout
if (tax > 10) {
const note = "High tax"; // local to this if block
console.log(note);
}
// console.log(note); → ReferenceError: note is not defined
return total + tax;
}
// console.log(tax); → ReferenceError: tax is not definedInner code can read outer variables (checkout can use siteName), but outer code cannot see inside. Parameters are local to their function.
Scope is a feature, not an obstacle. Local variables can't be accidentally changed by distant code, and two functions can each use a variable called total without interfering. A good rule is to declare variables in the smallest scope that works and to avoid global variables whenever possible.
Shadowing: if a local variable has the same name as an outer one, the local one wins inside its block. It's legal but confusing, so prefer distinct names.
Step 9 of 13Practice · Diagram
Scope is nested like boxes
Code can look outward to enclosing scopes, never inward.
Code in which layer can read all of siteName, tax and note?
Tap the shape that answers the question, then press Check.
- Global: siteName
Visible everywhere in the file.
- Function checkout: total, tax
Visible inside checkout, including its inner blocks.
- if block: note
Visible only between the braces of that if.
Step 10 of 13Practice · True or false
A variable declared with const inside a function can be read by code outside that function.
Step 11 of 13Note
Step 12 of 13Tap to reveal
Function declarations versus arrow functions
Hoisting
A function declaration (function add(a, b) { ... }) is hoisted: JavaScript makes it available before the line where it appears, so you can call it near the top of a file. A function stored in a const, including arrow functions, only exists after that line runs. Calling it earlier throws a ReferenceError.
The this keyword
Regular functions get their own this, which depends on how they are called. Arrow functions do not have their own this; they use the this of the surrounding code. That makes arrows ideal for short callbacks inside methods, and regular functions better for object methods that need this to point at the object.
Readability
Many teams use declarations for named, top-level functions, because the name stands out, and arrow functions for short callbacks passed to map, filter, addEventListener and setTimeout.
What stays the same
Both kinds take parameters, return values and create their own scope. Choosing one is mostly about style and the this rule, not about what they can calculate.
Step 13 of 13Practice · Code challenge
Write an arrow function isEven that takes a number and returns true if it is even and false otherwise. Assign it to a const.
isEven(4)isEven(7)isEven(0)isEven(-2)
Lesson complete!