Mutations, Rest Parameter, and Spread Operator

Mutations

Reference data types like objects, arrays, and functions assigned to variables using let and const are mutable. But primitive data types like boolean, number, string, etc. are not mutable (immutable).

Immutability means we want to preserve/keep our current state. Mutating means the opposite.

const x = [1, 2, 3];
x[1] = 30;
console.log(x); // will display [1, 30, 3] because we mutated index [1], changing 2 to 30.

Note: Object.freeze(param) will prevent mutation.

Rest Parameter

With ES6 came the rest parameter for functions. With this, we can now create more flexible functions that can take a variable amount of arguments, which are stored in an array.

const sum = (...args) => {
    return args.reduce((x, y) => x + y, 0);
    // 0 is just the starter value
    // reduce creates one value from multiple args in this situation
}
console.log(sum(5, 10, 20)); // 35

Spread Operator

ES6 came out with the ... notation, which can be used with rest parameters and spread operators.

  • With rest parameters, the ... means it will collect “the rest” of the elements into an array (it must be the last parameter).
  • With spread operators, the ... means that arrays, objects, and strings can be turned into single arguments/elements.
const food = ["Pizza", "Sushi", "Fruit"];
const moreFood = ["Wings", "Fish", ...food];
console.log(moreFood);
// ["Wings", "Fish", "Pizza", "Sushi", "Fruit"]

The spread operator allows you to expand an array into individual elements, making it easy to copy or combine arrays.