JSJavaScript
BeginnerLesson 5 of 16

Functions – JavaScript

Declarations, arrow functions, default values and rest parameters.

In JavaScript, functions are values like any other: you can store them in variables, pass them around and return them. The classic form is the function declaration:

function begruesse(name, gruss = "Hello") {
  return gruss + ", " + name + "!";
}
console.log(begruesse("Ada"));
console.log(begruesse("Linus", "Hi"));

Arrow functions are the short notation – especially for small callbacks. With exactly one expression, the return can be omitted:

const quadrat = x => x * x;
const addiere = (a, b) => a + b;
const teile = (a, b) => {
  if (b === 0) return null;
  return a / b;
};
console.log(quadrat(5), addiere(2, 3), teile(1, 0));
console.log([1, 2, 3].map(quadrat));

With rest parameters (...) you collect any number of arguments into an array. JavaScript has no named arguments – pass an object instead and destructure it in the signature:

function summe(...zahlen) {
  return zahlen.reduce((a, b) => a + b, 0);
}
console.log(summe(1, 2, 3, 4));   // 10

function zeichne({ breite = 10, hoehe = 5, farbe = "blue" } = {}) {
  return breite + "x" + hoehe + " " + farbe;
}
console.log(zeichne({ farbe: "red" }));   // 10x5 red
console.log(zeichne());                   // 10x5 blue
WarningWithout return, a function returns undefined. To return an object literal directly from an arrow function, you need parentheses: const f = () => ({ a: 1 }) – otherwise {} is read as the function body.
TipFunction declarations are "hoisted": you may call them before their definition. With const f = () => ... that does not work – there the variable is only usable after that line.