Wednesday, December 4, 2019

Destructuring and Spreading in JavaScript

I wanted to get a better understanding of destructuring and spreading for a project I am working on. So I created this jsfiddle to understand it better.

What I really wanted to know was would happen if I tried to unpack a value from an object that did not exist. And then what would subsequently happen if I tried to use that value in a spread operation. For example:
const testObj = {
    a: [1, 2, 3],
    b: [4, 5, 6]
}

const { a } = testObj;
const { b } = testObj;
const { c } = testObj;

const combined = [...a, ...b, ...c];

The short answer is this: if you try to destructure a non-existent property, then you get an undefined value. And if you try to use that undefined value in a spread operation, JavaScript will throw an error: TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
 
Blogger Templates