Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Modern JavaScript Essentials | Section
JavaScript Essentials for React Native Development

bookModern JavaScript Essentials

Swipe to show menu

Destructuring and the spread operator are two features that make your JavaScript code cleaner and easier to read, especially when working with arrays and objects. With destructuring, you can quickly extract values from arrays or properties from objects and assign them to variables in a single line. This is much more concise than accessing each value one by one, and it helps avoid repetitive code.

12345678910111213141516171819202122
// Array destructuring const rgb = [255, 100, 50]; const [red, green, blue] = rgb; console.log(red); // 255 console.log(green); // 100 console.log(blue); // 50 // Object destructuring const user = { name: "Alex", age: 28, city: "New York" }; const { name, age } = user; console.log(name); // "Alex" console.log(age); // 28 // Spread operator to copy arrays const numbers = [1, 2, 3]; const moreNumbers = [...numbers, 4, 5]; console.log(moreNumbers); // [1, 2, 3, 4, 5] // Spread operator to merge objects const address = { city: "Boston", zip: "02118" }; const fullProfile = { ...user, ...address }; console.log(JSON.stringify(fullProfile)); // { name: "Alex", age: 28, city: "Boston", zip: "02118" }
copy

The spread operator (...) lets you copy arrays or objects, merge them, or add new items or properties easily. This is especially useful in React, where you often need to update state without mutating the original data. For example, you might use the spread operator to create a new array with updated values, or to merge two objects into a single object.

Common patterns in React include using array and object destructuring to access props or state, and using the spread operator to update lists or combine component properties. These features help you write code that is both concise and easy to maintain.

question mark

What does the spread operator (...) do?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 10

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 10
some-alt