Domů O mně Služby Portfolio Učím Blog Kontakt
← Zpět na učím

03.07 Rest parametry

Výuka

Proč rest parametry?

Dosud jsme viděli funkce s pevným počtem parametrů. Ale co když nevíš, kolik argumentů bude předáno?

// ❌ Musíš znát přesný počet
const sum2 = (a, b) => a + b;
const sum3 = (a, b, c) => a + b + c;
// A co když chceš sčítat 10 čísel?

Rest parametry (ES6+) umožňují funkci přijmout libovolný počet argumentů:

// ✅ Funguje s jakýmkoli počtem argumentů
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);

sum(1, 2);          // 3
sum(1, 2, 3, 4, 5); // 15

Proč je to užitečné?

  • Flexibilní funkce - nemusíš znát počet argumentů dopředu
  • Čistší API - Math.max(1, 2, 3, 4) místo Math.max([1, 2, 3, 4])
  • Skutečné pole - na rozdíl od starého arguments objektu

Představ si to jako: Balíček "všechno ostatní". Když posíláš dárky, první je pro maminku, druhý pro tátu, a zbytek (...rest) pro sourozence.

Jak to funguje?

1. Napíšeš ...nazev jako POSLEDNÍ parametr: function(...args) { }
2. Všechny "zbývající" argumenty se sbalí do POLE
3. Můžeš kombinovat s běžnými parametry: function(first, ...rest) { }
4. Rest MUSÍ být poslední - jinak JavaScript neví, kde končí rest

Důležité:

  • Rest parametr je skutečné pole (Array), ne objekt jako starý arguments
  • Můžeš používat pole metody: map, filter, reduce atd.
  • Funguje s arrow funkcemi (arguments ne!)

Klíčové koncepty

  • ... (tři tečky) - rest operator sbírá zbylé argumenty do pole
  • Musí být poslední - function(a, ...rest, b) nefunguje!
  • Je to pole - můžeš volat rest.map(), rest.length atd.
  • Rest vs arguments - rest je modernější, čistší, funguje všude

JavaScript

Příklad 1: Základní rest parametr

const sum = function(...numbers) {
  console.log(numbers);  // Je to pole!
  return numbers.reduce((a, b) => a + b, 0);
};

console.log(sum(1, 2, 3));
// numbers = [1, 2, 3]
// → 6

console.log(sum(1, 2, 3, 4, 5));
// numbers = [1, 2, 3, 4, 5]
// → 15

console.log(sum(5));
// numbers = [5]
// → 5

console.log(sum());
// numbers = []
// → 0

Co se stalo?

  • ...numbers sbírá všechny argumenty do pole
  • Pole může být prázdné ([]) pokud nepředáš žádné argumenty
  • Můžeš použít jakékoli pole metody (reduce, map, filter)

Příklad 2: Kombinace běžných parametrů a rest

const greetAll = function(greeting, ...names) {
  console.log("greeting:", greeting);  // První argument
  console.log("names:", names);        // Zbylé argumenty jako pole

  return names.map(name => greeting + " " + name);
};

console.log(greetAll("Hello", "Alice", "Bob", "Charlie"));
// greeting: "Hello"
// names: ["Alice", "Bob", "Charlie"]
// → ["Hello Alice", "Hello Bob", "Hello Charlie"]

Co se stalo?

  • První parametr (greeting) dostane první argument
  • Rest parametr (...names) dostane všechno ostatní
  • Rest musí být poslední - nemůžeš psát function(...names, greeting)

Příklad 3: Rest parametr je skutečné pole

const max = function(...numbers) {
  // Můžeš používat pole metody
  console.log(numbers.length);        // Počet argumentů
  console.log(numbers[0]);            // První číslo
  console.log(numbers.includes(5));   // Obsahuje 5?

  return Math.max(...numbers);        // Spread operator
};

console.log(max(1, 5, 3, 9, 2));
// → 9

Co se stalo?

  • ...numbers je skutečné pole (Array)
  • Můžeš volat jakékoliv pole metody: map, filter, reduce, includes, length atd.
  • To je obrovská výhoda oproti starému arguments!

Příklad 4: Porovnání se starým arguments

Starý způsob - arguments (před ES6):

function oldSum() {
  // arguments NENÍ pole!
  console.log(Array.isArray(arguments));  // false

  // Musíš ho převést na pole
  const nums = Array.from(arguments);
  return nums.reduce((a, b) => a + b, 0);
}

Nový způsob - rest parameters (ES6+):

const newSum = function(...numbers) {
  // numbers JE pole!
  console.log(Array.isArray(numbers));  // true

  // Můžeš rovnou použít metody
  return numbers.reduce((a, b) => a + b, 0);
};

Co se stalo?

  • arguments je objekt, ne pole - musíš ho převádět
  • ...rest je pole - můžeš rovnou používat metody
  • arguments nefunguje v arrow funkcích, ...rest funguje všude!

Příklad 5: Rest s arrow funkcemi

// ✅ Rest funguje s arrow funkcemi
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);

// ❌ arguments NEFUNGUJE s arrow funkcemi
const badSum = () => {
  return arguments.reduce((a, b) => a + b, 0);  // Error: arguments is not defined
};

Příklad 6: Praktický příklad - logger

const log = function(level, ...messages) {
  const timestamp = new Date().toISOString();
  const combined = messages.join(" ");
  console.log(`[${timestamp}] [${level}] ${combined}`);
};

log("INFO", "Server", "started", "successfully");
// → [2025-12-18T10:30:00.000Z] [INFO] Server started successfully

log("ERROR", "Database", "connection", "failed");
// → [2025-12-18T10:30:01.000Z] [ERROR] Database connection failed

Co se stalo?

  • První parametr (level) je povinný
  • Rest (...messages) sbírá všechny další argumenty
  • Spojíme je pomocí join(" ") do jednoho textu

TypeScript

V TypeScriptu musíš specifikovat typ pole pro rest parametr:

// Rest parametr s typem number[]
const sum = function(...numbers: number[]): number {
  return numbers.reduce((a, b) => a + b, 0);
};

// Rest parametr s typem string[]
const greetAll = function(greeting: string, ...names: string[]): string[] {
  return names.map(name => greeting + " " + name);
};

// TypeScript kontroluje typy
sum(1, 2, 3);       // ✅ OK
sum("a", "b");      // ❌ Error: Argument of type 'string' is not assignable to parameter of type 'number'

greetAll("Hi", "Alice", "Bob");  // ✅ OK
greetAll("Hi", 1, 2);            // ❌ Error: čísla nejsou string

TypeScript kontroluje:

  • Typ prvků v poli - všechny argumenty musí být správného typu
  • Pozice rest parametru - musí být poslední
  • Použití pole metod - ví, že rest je pole

Rozdíl JS vs TS

JavaScript:

const sum = function(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
};

sum(1, 2, 3);       // 6 ✅
sum("1", "2", "3"); // "0123" ⚠️ (string concatenation, ne chyba!)
sum(1, "2", true);  // "102true" ⚠️ (wtf?!)

TypeScript:

const sum = function(...numbers: number[]): number {
  return numbers.reduce((a, b) => a + b, 0);
};

sum(1, 2, 3);       // 6 ✅
sum("1", "2", "3"); // ❌ Error: Argument of type 'string' is not assignable to parameter of type 'number'
sum(1, "2", true);  // ❌ Error: smíšené typy

Tip

💡 Vždy používej rest místo arguments:

// ❌ Starý způsob - arguments
function oldWay() {
  const args = Array.from(arguments);  // Musíš převádět
  return args.reduce((a, b) => a + b);
}

// ✅ Nový způsob - rest
const newWay = (...args) => args.reduce((a, b) => a + b);

💡 Rest musí být poslední:

// ❌ Nefunguje - rest není poslední
function bad(...rest, last) {  // SyntaxError!
}

// ✅ Funguje - rest je poslední
function good(first, ...rest) {
  console.log(first);  // První argument
  console.log(rest);   // Všechno ostatní
}

💡 Kombinuj s destrukturováním pro čistější kód:

const log = function(level, ...messages) {
  const [first, ...others] = messages;  // Destrukturování

  console.log(`[${level}] ${first}`);
  if (others.length > 0) {
    console.log("Additional:", others.join(", "));
  }
};

log("INFO", "Server started", "port 3000", "ready");
// → [INFO] Server started
// → Additional: port 3000, ready

Kvíz

Co platí o rest parametru?

- Rest parametr MUSÍ být poslední! function(...rest, x) je chyba

- Rest sbírá zbylé argumenty do skutečného pole (Array)

- Rest parametr je součástí ES6 (JavaScript), ne jen TypeScriptu

- Rest je pole, arguments je objekt - úplně jiné!

🎯 Závěrečný projekt

Po dokončení všech 8 dílů vytvoříte jednoduchou Todо aplikaci v čistém JavaScriptu. Naučíte se, jak aplikovat vše, co jste se naučili, na reálný projekt.

Zobrazit podrobnosti projektu →

Připraveni začít?

Zaregistrujte se a získejte přístup ke všem dílům tohoto seriálu

Kontaktujte mě

Informace o seriálu

Obtížnost

Délka

Cca 480 minut

Počet videí

8 videí + projekty

Certifikát

Po dokončení obdržíte certifikát


Lekce v této sekci


Struktura lekcí (souborový strom)

06. Typescript specifika
  • v přípravě
08. Moduly tridy
  • v přípravě
09. React zaklady
  • v přípravě
10. React hooks
  • v přípravě
12. Nextjs server
  • v přípravě
13. Databaze auth
  • v přípravě
14. Nextjs pokrocile
  • v přípravě