Modern JavaScript Essentials
Свайпніть щоб показати меню
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" }
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.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат