JavaScript Destructuring
Destructuring in JavaScript extracts values from arrays or properties from objects and assigns them to variables in a single, concise statement. It simplifies working with complex arrays and objects by reducing repetitive code.
Array Destructuring
Array destructuring extracts values from arrays in order, assigning them to variables in a single statement:
const colors = ['red', 'green', 'blue'];const [firstColor, secondColor, thirdColor] = colors;console.log(firstColor);console.log(secondColor);console.log(thirdColor);
The output for this is:
redgreenblue
Items that aren’t needed can also be skipped:
const colors = ['red', 'green', 'blue'];const [primaryColor, , tertiaryColor] = colors;console.log(tertiaryColor); // Output: blue
Object Destructuring
Object destructuring extracts specific properties from an object using their key names:
const car = { make: 'Toyota', model: 'Camry', year: 2021 };const { make, model } = car;console.log(make); // Output: Toyotaconsole.log(model); // Output: Camry
The output for this code is:
ToyotaCamry
Variables can also be renamed or assigned default values:
const car = { make: 'Toyota', model: 'Camry', year: 2021 };const { model: carModel, color = 'white' } = car;console.log(carModel); // Output: Camryconsole.log(color); // Output: white
Nested Destructuring
Destructuring also supports nested structures for deeply nested objects or arrays:
const user = {id: 1,info: { name: 'Alice', address: { city: 'Seattle', zip: 98101 } },};const {info: {name,address: { city },},} = user;console.log(name);console.log(city);
The output of this code is:
AliceSeattle
Codebyte Example
The following codebyte example uses nested destructuring to extract values directly from an object:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours