Wrap Code Once, Use It Anywhere
JavaScript Functions
A function is a named, reusable block of code. Declare it, call it, return a value — the unit of abstraction in JavaScript.
What you'll learn
- Declare a function and call it
- Return a value
- Know the difference between declaration and expression
A function is a named, reusable block of code. Write it once, call it whenever you need it.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Ada")); // "Hello, Ada!"
console.log(greet("Lin")); // "Hello, Lin!" Three parts:
- Declaration:
function greet(name) { … } - Parameters:
name— values the caller passes in. return: the value the function gives back.
Calling a Function
Use the function’s name followed by () — pass any arguments inside.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(10, 20) + 1); // 31 (the result is a value) Returning a Value
return exits the function and hands a value back to the caller. Once
return runs, the function is done — code after it doesn’t execute.
function classify(n) {
if (n > 0) return "positive";
if (n < 0) return "negative";
return "zero";
}
console.log(classify(5)); // "positive"
console.log(classify(-3)); // "negative"
console.log(classify(0)); // "zero" If a function doesn’t return anything, it returns undefined.
function shout(text) {
console.log(text.toUpperCase());
}
const result = shout("hello");
console.log(result); // undefined ← no return Declaration vs Expression
Two ways to define a function.
Declaration — uses the function keyword as a statement:
function add(a, b) {
return a + b;
} Expression — assigns a function to a variable:
const add = function (a, b) {
return a + b;
}; Both create callable functions. The differences:
- Declarations are hoisted — you can call them before the line where they’re written.
- Expressions aren’t — you have to declare before you call.
// ✅ Declaration: can be called before its definition
console.log(declared()); // "I work"
function declared() {
return "I work";
}
// ❌ Expression: ReferenceError if called too early
// console.log(expressed());
const expressed = function () {
return "I work";
}; Anonymous Functions
A function expression doesn’t need a name — you can leave it anonymous and refer to it through the variable.
const square = function (n) {
return n * n;
};
console.log(square(4)); // 16 You’ll see anonymous functions most often as callbacks — passed to
methods like map, filter, setTimeout. Arrow functions (coming
up) are usually a nicer fit.
Try It Yourself
Exercise
Write a double function
// declare double here
console.log(double(7));
💡 Show hint
✅ Show solution
function double(n) {
return n * 2;
}
console.log(double(7));
Up Next
A deeper look at parameters — defaults, rest, destructuring.
JavaScript Function Parameters →