Destructuring in JavaScript

Level 4241 keystrokes

This demonstrates object and array destructuring with rest operator.

JavaScript code

// Create an object with three properties
1const person = {
2 name: "John",
3 age: 30,
4 city: "Tokyo"
5};
6
// Object destructuring: extract properties into variables
// Variable names must match property names
7const { name, age } = person;
8console.log(`${name} is ${age} years old`);
9
// Create an array of numbers
10const numbers = [1, 2, 3, 4, 5];
// Array destructuring: extract elements by position
// ...rest collects remaining elements into an array
11const [first, second, ...rest] = numbers;
// first=1, second=2, rest=[3,4,5]
12console.log(first, second, rest);

Output

John is 30 years old
1 2 [ 3, 4, 5 ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ,× 11
  • ;× 6
  • .× 5
  • "× 4
  • {× 4
  • }× 4
  • =× 4
  • :× 3
  • (× 2
  • )× 2

More JavaScript examples at level 4

← JavaScript typing practice