Functions in JavaScript
Introduction
A function packages steps you can run by name, with parameters, many times. Functions are first-class values in JavaScript—you can pass them around, return them, and store them in variables. This chapter explains why functions matter and previews declaration styles used throughout the rest of the course.
Prerequisites
Why Functions Exist
Without functions, every script repeats the same blocks. Functions give you:
- Reuse — one definition, many calls
- Names —
sendEmail()reads better than 40 anonymous lines - Testing — isolate behavior in small units
- Abstraction — hide details behind a clear interface
Function Declaration
// Hoisted declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));Function Expression
// Stored in a variable
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3));Arrow Functions (Preview)
// Short syntax for expressions
const double = (n) => n * 2;
console.log(double(4));Details in this and arrow functions.
Calling vs Defining
// define once
function logLine(message) {
console.log(`[log] ${message}`);
}
// call many times
logLine("server started");
logLine("request received");Parameters and Return Values
Functions accept arguments; return sends a value back (or undefined if omitted). See parameters chapter.
Functions as Values
// Pass function to another function
function runTwice(fn) {
fn();
fn();
}
runTwice(() => console.log("tick"));Mini Example: Format Currency
// Reusable formatter
function formatUSD(amount) {
return `$${amount.toFixed(2)}`;
}
console.log(formatUSD(19.5));
console.log(formatUSD(1000));FAQ
Declaration vs expression?
Declarations are hoisted; expressions are not—order matters for const fn = function....
Do I need return?
Without return, the function yields undefined.
Are arrow functions always better?
No—use arrows for short callbacks; use function when you need this binding (see this and arrows).