unpack
Array & Object Destructuring
data_array
Array Destructuring
// Tanpa destructuring
const colors = ['red', 'green', 'blue'];
const first = colors[0];
const second = colors[1];
// Dengan destructuring
const [first, second, third] = colors;
// Skip element
const [first, , third] = colors;
const colors = ['red', 'green', 'blue'];
const first = colors[0];
const second = colors[1];
// Dengan destructuring
const [first, second, third] = colors;
// Skip element
const [first, , third] = colors;
category
Object Destructuring
// Tanpa destructuring
const person = {
name: 'John',
age: 30,
city: 'Jakarta'
};
const name = person.name;
const age = person.age;
// Dengan destructuring
const {name, age, city} = person;
const person = {
name: 'John',
age: 30,
city: 'Jakarta'
};
const name = person.name;
const age = person.age;
// Dengan destructuring
const {name, age, city} = person;
Kode lebih ringkas - Ekstrak nilai dengan satu baris kode
Lebih mudah dibaca - Jelas variabel apa yang diekstrak
code
Contoh Praktis
// API Response
const response = {
data: {
users: [
{id: 1, name: 'Alice', email: 'alice@example.com'},
{id: 2, name: 'Bob', email: 'bob@example.com'}
],
total: 2
},
status: 'success'
};
// Nested destructuring
const {data: {users, total}} = response;
// Function parameters
const displayUser = ({name, email}) => {
console.log(`${name}: ${email}`);
};
const response = {
data: {
users: [
{id: 1, name: 'Alice', email: 'alice@example.com'},
{id: 2, name: 'Bob', email: 'bob@example.com'}
],
total: 2
},
status: 'success'
};
// Nested destructuring
const {data: {users, total}} = response;
// Function parameters
const displayUser = ({name, email}) => {
console.log(`${name}: ${email}`);
};
Output:
users = [{id: 1, name: 'Alice', ...}, {id: 2, name: 'Bob', ...}]
total = 2
users = [{id: 1, name: 'Alice', ...}, {id: 2, name: 'Bob', ...}]
total = 2
lightbulb
Destructuring sangat efisien untuk bekerja dengan API response dan props di React