Destructuring in JavaScript
Pulling values out of objects and arrays by shape.
const user = { id: 7, name: "ada", city: "london" };
const { name, city: town, country = "uk" } = user;
const colors = ["red", "green", "blue"];
const [first, ...rest] = colors;
function describe({ id, name }) {
return `#${id} ${name}`;
}
const label = describe(user);
const swapped = [colors[1], colors[0]];
How it works
- Object patterns can rename and supply defaults.
...restcollects whatever the pattern didn't name.- A parameter can be destructured in the signature.
Keywords and builtins used here
constfunctionreturn
The run, in numbers
- Lines
- 12
- Characters to type
- 311
- Tokens
- 98
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 65 seconds.
Step 2 of 3 in Functions, step 15 of 43 in Language basics.