Functions
Reusable blocks of code — declarations, expressions, arrow functions, default parameters, and first-class functions.
Passing a function straight into map looks tidy: strings.map(parseInt). But map calls its callback with three arguments (the value, its index and the array), and parseInt treats its second argument as the number base. So the second item is parsed in base 1 and the third in base 2. Three identical strings come back as three different results, with no error.
const fromCsv = ["10", "10", "10"];
console.log(fromCsv.map(parseInt)); // [ 10, NaN, 2 ]Writing reusable code with functions
Imagine you need to calculate a discount on a price. You write the calculation once. Then you need to apply it to 50 products. Without functions, you'd copy-paste the same calculation 50 times. With a function, you write it once and call it 50 times. Functions are the fundamental unit of reusability.
Three ways to write a function
1. Function declaration — the traditional way:
function calculateDiscount(price, discountPercent) {
const discount = price * (discountPercent / 100);
return price - discount;
}
console.log(calculateDiscount(100, 20)); // 80
console.log(calculateDiscount(50, 10)); // 452. Function expression — assigned to a variable:
const calculateTax = function(price, rate) {
return price * rate;
};
console.log(calculateTax(100, 0.18)); // 183. Arrow function — modern, concise, preferred for short functions:
// Full arrow function:
const greet = (name) => {
return `Hello, ${name}!`;
};
// Shorthand: single expression — no braces, no return needed
const greetShort = (name) => `Hello, ${name}!`;
// Single parameter — parentheses optional
const double = n => n * 2;
// No parameters — empty parentheses required
const getRandom = () => Math.random();
console.log(greet("Alice")); // "Hello, Alice!"
console.log(double(7)); // 14
console.log(getRandom()); // some random numberWhen to use which
- Arrow functions for callbacks and short operations:
array.map(x => x * 2) - Function declarations for named, top-level functions you'll call from many places
- Avoid function expressions in most cases — arrow functions do the same with less code
Parameters and arguments
// Parameters are the names in the definition:
function add(a, b) { // a and b are parameters
return a + b;
}
// Arguments are the actual values you pass when calling:
add(3, 5); // 3 and 5 are argumentsDefault parameters
// If an argument is missing, use the default value:
function createUser(name, role = "viewer", isActive = true) {
return { name, role, isActive };
}
console.log(createUser("Alice", "admin"));
// { name: "Alice", role: "admin", isActive: true }
console.log(createUser("Bob"));
// { name: "Bob", role: "viewer", isActive: true } — defaults usedRest parameters — variable number of arguments
// ...name collects all extra arguments into an array:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2)); // 3
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum()); // 0return — sending a value back
function isAdult(age) {
return age >= 18; // sends true or false back to the caller
}
const result = isAdult(20);
console.log(result); // true
// A function without return gives back undefined:
function logMessage(msg) {
console.log(msg);
// no return — returns undefined
}
console.log(logMessage("hi")); // logs "hi", then logs undefinedFunctions are values — first-class functions
This is one of JavaScript's most important ideas: functions are values, just like numbers and strings. You can store them in variables, put them in arrays, pass them to other functions, and return them from functions.
// Store in a variable (already seen):
const greet = name => `Hello, ${name}!`;
// Pass to another function (callback):
const names = ["Alice", "Bob", "Charlie"];
const greeted = names.map(name => `Hello, ${name}!`);
console.log(greeted);
// ["Hello, Alice!", "Hello, Bob!", "Hello, Charlie!"]
// A function that takes another function as a parameter:
function doTwice(fn, value) {
return fn(fn(value));
}
const addTen = n => n + 10;
console.log(doTwice(addTen, 5)); // 25 (5 → 15 → 25)Official Sources
- MDN Web Docs — Functions
- MDN Web Docs — Arrow function expressions
- MDN Web Docs — Default parameters
- ECMAScript 2024 — Function Objects (§10.2)
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.