Destructuring
๐จโ๐ผ Destructuring is a modern JavaScript syntax that lets you extract values
from objects and arrays into variables in a clean, readable way.
Object destructuring:
const person = { name: 'Alice', age: 30, city: 'NYC' }
// Without destructuring:
const name = person.name
const age = person.age
// With destructuring:
const { name, age } = person
Array destructuring:
const colors = ['red', 'green', 'blue']
// Without destructuring:
const first = colors[0]
const second = colors[1]
// With destructuring:
const [first, second] = colors
- Create a
userobject withusername,email, andisAdminproperties - Use object destructuring to extract
usernameandemailinto variables - Create an array
scoreswith 3 numbers - Use array destructuring to extract the first two scores
- Log all the destructured variables
๐ฐ You can also rename during destructuring:
const { name: userName } = person // userName = "Alice"