Spread and Rest Operators

Verze:

19. 06. 2025

Zodpovědná osoba:

Dominik Šlechta

Spread operator SHOULD be used for copying and merging arrays/objects. Rest operator SHOULD be used for collecting remaining elements.

Spread Operator

  • Rule: The spread operator (...) SHOULD be used for copying and merging arrays and objects.

  • Reason: Spread operator provides a clean, readable syntax for operations that would otherwise require verbose methods like Object.assign() or Array.concat().

Example (Arrays):

// Copying an array
const original = [1, 2, 3];
const copy = [...original];

// Merging arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]

// Adding elements
const withNew = [...original, 4, 5]; // [1, 2, 3, 4, 5]

Example (Objects):

// Copying an object
const user = { name: 'John', age: 30 };
const copy = { ...user };

// Merging objects
const defaults = { theme: 'light', lang: 'en' };
const settings = { theme: 'dark' };
const merged = { ...defaults, ...settings }; // { theme: 'dark', lang: 'en' }

// Adding properties
const extended = { ...user, email: 'john@example.com' };

Rest Operator

  • Rule: The rest operator (...) SHOULD be used for collecting remaining elements in destructuring and function parameters.

  • Reason: Rest operator simplifies working with variable numbers of arguments and extracting subsets of data.

Example (Function Parameters):

// Collecting remaining arguments
function sum(first: number, ...rest: number[]): number {
	return rest.reduce((acc, val) => acc + val, first);
}

sum(1, 2, 3, 4); // 10

Example (Destructuring):

// Array destructuring with rest
const [first, second, ...remaining] = [1, 2, 3, 4, 5];
// first = 1, second = 2, remaining = [3, 4, 5]

// Object destructuring with rest
const { name, ...otherProps } = { name: 'John', age: 30, city: 'NYC' };
// name = 'John', otherProps = { age: 30, city: 'NYC' }

Summary:

  • Spread operator SHOULD be used for copying and merging arrays/objects.
  • Rest operator SHOULD be used for collecting remaining elements.