Ad space (banner)
🟨JavaScript Lessons
Lesson 12 / 69

Destructuring and the Spread Syntax

In this lesson you'll master destructuring and the spread syntax in JavaScript so you can efficiently pull values out of, or combine, objects and arrays. This is for people searching "JavaScript destructuring usage" or "JavaScript spread syntax."

Destructuring lets you pull values out of an object or array all at once. Writing const { name, age } = user; extracts user.name and user.age into two separate variables in a single step. The spread syntax (...) is used to expand and copy, or combine, arrays and objects. Both are modern styles that show up constantly in real-world code.

The sample code destructures name and age out of the object user, and expands the array nums with the spread syntax to build a new array, newNums, with extra elements added. Values that used to take several lines to extract one at a time can now be pulled out in a single line, making code more readable and dramatically cutting down how much you have to write.

A common beginner stumbling block is that the names you use in destructuring must match the original property names. Specifying a property name that doesn't exist doesn't throw an error — it just becomes undefined. Also be careful: the spread syntax only creates a "shallow copy," so nested objects don't get duplicated all the way down.

In real development, this is now an indispensable notation for writing modern JavaScript — pulling just the values you need out of an object passed as a function argument, or, in a library like React, using the spread syntax to copy existing state before changing just part of it when updating state.

Destructuring also lets you rename the variable you're extracting into. Writing const { name: userName } = user; lets you receive the value of the name property under a different variable name, userName — handy when you want to avoid colliding with the original property name.

Object destructuring also lets you specify a default value at the same time. Writing const { age = 18 } = user; means that if the age property doesn't exist, 18 is automatically used — a mechanism similar to default arguments.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)