Function Basics in JavaScript
Function Basics in JavaScript
~12 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
Functions are reusable blocks of code – time to turn our category icon logic from chapter 6 into a real function, instead of rewriting it every time.
Function declarations
function getIcon(category) {
switch (category) {
case 'Rent':
return '????';
case 'Salary':
return '????';
case 'Leisure':
return '????';
default:
return '????';
}
}
console.log(getIcon('Rent')); // '????'return ends the function IMMEDIATELY and yields the given value – code after it in the same function body never runs. A function WITHOUT a return statement implicitly returns undefined.
Parameters vs. arguments
A subtle, often-conflated distinction: parameters are the placeholders in the function definition (category above), arguments are the actual values passed at call time ('Rent' above).
Default parameters
function formatAmount(amount, currency = 'EUR') {
return `${amount.toFixed(2)} ${currency}`;
}
console.log(formatAmount(2400)); // '2400.00 EUR'
console.log(formatAmount(2400, 'USD')); // '2400.00 USD'A default value only kicks in when the argument is undefined (not yet present) or explicitly omitted – formatAmount(2400, undefined) also uses 'EUR', whereas formatAmount(2400, null) does NOT, since null is a deliberately set value.
Rest parameters: any number of arguments
function sum(...amounts) {
let total = 0;
for (const amount of amounts) {
total += amount;
}
return total;
}
console.log(sum(100, 200, 50)); // 350
console.log(sum(2400, -850, -300, -120)); // 1130...amounts collects ALL passed arguments into a real array – more on ... syntax (which also appears as the spread operator in a different role) in chapter 13.
Function declarations get hoisted
A quirk that sets function declarations apart from most other declarations: they can be called BEFORE their actual definition in the code, because the engine already fully registers the whole function definition while reading the file ("hoisting", covered in depth in chapter 15):
console.log(doubleValue(21)); // 42 - works even though the call is BEFORE the definition!
function doubleValue(value) {
return value * 2;
}Function expressions
Alternatively, a function can also be assigned to a variable as an EXPRESSION – this form lacks the hoisting behavior above, the variable must be assigned BEFORE the call:
const tripleValue = function (value) {
return value * 3;
};
console.log(tripleValue(10)); // 30Tipp: In practice, function expressions today are mostly written as arrow functions – the entire next chapter covers that.