Lesson 2 of 6 · 5 min
Functions
Declare and call functions, parameters with defaults, return values, arrow functions, scope and closures, and passing functions as values.
On this page
A function is a named, reusable block of code. You define it once and call it as often as you need.
Declaring and calling
function greet(name) {
return `Hello, ${name}!`
}
greet("Asha") // "Hello, Asha!"
nameis a parameter: a variable that holds whatever value the caller passes in."Asha"is the argument: the value passed in.returnsends a value back and ends the function. A function withoutreturngives backundefined.
Default parameters
function price(amount, taxRate = 0.18) {
return Math.round(amount * (1 + taxRate))
}
price(1000) // 1180
price(1000, 0.05) // 1050
Arrow functions
A shorter way to write a function, especially a small one:
const double = (n) => n * 2
const add = (a, b) => a + b
const toUser = (name) => ({ name, active: true }) // wrap an object in brackets
double(4) // 8
With one expression, the result is returned automatically. With braces, you need return:
const total = (items) => {
let sum = 0
for (const item of items) sum += item.price
return sum
}
Scope
Variables declared inside a function (or any { } block) with let or const exist only inside it:
function setup() {
const secret = 42
}
console.log(secret) // ReferenceError: secret is not defined
Inner code can read outer variables, but not the other way round. Keeping variables in the smallest scope that works prevents accidental clashes.
Closures
A function remembers the variables around it when it was created, even after the outer function has finished:
function makeCounter() {
let count = 0
return () => {
count++
return count
}
}
const next = makeCounter()
next() // 1
next() // 2
count is private: nothing outside can change it except through next. Closures are behind many everyday patterns, including event handlers and React hooks.
Functions are values
You can store a function in a variable, pass it to another function, and return it. A function passed in to be called later is a callback:
function repeat(times, action) {
for (let i = 0; i < times; i++) action(i)
}
repeat(3, (i) => console.log(`Run ${i}`))
setTimeout(() => console.log("One second later"), 1000)
Small, focused functions
Good functions do one thing, have a name that says what that is, and take their inputs as parameters rather than reaching for outside variables. They are easier to test, reuse and read:
const formatPrice = (amount) =>
new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount)
formatPrice(18999) // "₹18,999.00"
Try it
Write isEven(n) that returns true or false. Then write makeGreeter(greeting) that returns a function, so that makeGreeter("Hi")("Asha") returns "Hi, Asha".
More from JavaScript Crash Course
- Lesson 4 · 5 minThe DOMFind elements with querySelector, change their text, attributes and classes, create and remove elements, and render a list from data safely.
- Lesson 5 · 5 minEventsRespond to clicks, typing and form submissions with addEventListener, use the event object, delegate events to a parent, and build a working theme toggle.
- Lesson 6 · 5 minAsync JavaScript and fetchWhy some code has to wait, promises, async and await, loading JSON from an API with fetch, handling errors and loading states, and running requests in parallel.