dev env

JavaScript Gotchas

Although JavaScript has come along way since it's inception as a tool which aimed to be more accessible to budding web enthusiasts, it still sports a somewhat ironically high amount of developer friction. This is a humble attempt at adding some clarity, so your mileage may vary. New sections will be added in time.

Gideon Kreitzer
2022/1/4
  1. Rest versus spread

The overloaded spread syntax

It's easy to get confused with the spread syntax when the same operator seems to perform opposite actions depending on the usage context. When using the spread syntax in a function signature to construct a rest parameter, it sequentially collects the arguments passed to that function and wraps them in a proper array.

However, when used in the body of a function, the spread operator seems to act more in line with what its name might suggest — that is to "spread out" or expand an array or object by reducing it to its immediate component parts. Imagine a Matryoshka doll being unpacked to expose its nested contents.

The following example uses the spread syntax as a rest parameter.

function rest(...collect) {
    const squared = collect.map(number => number**2)
    return squared
}

rest(5, 3, 2) // [25, 9, 4]

Next, we'll use the spread syntax as a spread or deconstruction operator on arrays.

function spreadArray(arr) {
    console.log(...arr)
}

function mergeArrays(arr) {
    return ['a', ...arr, 'z']
}

spreadArray([1,2,3]) // 1 2 3
mergeArrays([1,2,3]) // ['a', 1, 2, 3, 'z']

Finally, we'll deconstruct an object using spread.

// we use spread to merge the owned and 
// enumerable properties of two objects
function spreadObj(obj) {
    const day = { day: 'Thursday' }
    const merged = {
        ...obj,
        ...day,
    }
    console.log(merged)
}

spreadObj({ 'a': 1, 'b': 2 }) // { a: 1, b: 2, day: 'Thursday' }
Credits
Photo by Aleksandar Popovski
Tags
javascript gotchas tips