What are functions in JavaScript and how do you define one?
A function is a named, reusable block of code that can take inputs (parameters) and hand back a result with return.
Functions let you package a piece of logic once and call it as many times as you like with different inputs, instead of repeating yourself. You define one with the function keyword, list its parameters in (...), and use return to send a value back to whoever called it:
function formatiere(legende, zahl) {
let val = legende + ': ' + zahl;
return val;
}
console.log(formatiere('Höhe', 200)); // 'Höhe: 200'
console.log(formatiere('Breite', 8.0)); // 'Breite: 8'
Here formatiere ("format") takes a label and a number and returns them joined with a colon. Calling it twice with different arguments reuses the same logic.
Why functions matter:
- Structure — they break a big program into named, understandable pieces.
- DRY ("Don't Repeat Yourself") — write the logic once instead of copy-pasting it.
- Maintainability — fix or change behaviour in one place and every caller benefits.
A practical tip: give functions descriptive, verb-like names (calculateTotal, formatDate) so a reader instantly knows what they do.
Go deeper:
MDN: Functions guide — declarations vs expressions, default and rest parameters, and arrow functions.