Docs/JavaScript/Destructuring

Destructuring

Cara singkat untuk mengekstrak nilai dari array atau object ke variabel.

Array Destructuring

const [a, b, ...rest] = array

Object Destructuring

const { name, age } = object

Fitur Tambahan

  • Default values: const { x = 10 } = {}
  • Rename: const { name: userName } = obj
  • Nested: const { address: { city } } = obj
script.js
Try It →
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];

// Object destructuring
const user = { name: "Ali", age: 25, city: "Jakarta" };
const { name, age, country = "Indonesia" } = user;

// Nested
const data = { info: { title: "Dev", level: 5 } };
const { info: { title, level } } = data;

// Function parameter
const display = ({ name, age }) => name + " (" + age + ")";

const o = document.getElementById('output');
o.innerHTML = 
  '// Array
[first, second, ...rest] = [1,2,3,4,5]
→ first='+first+', second='+second+', rest='+JSON.stringify(rest)+'

'+
  '// Object
{ name, age, country="Indonesia" }
→ '+name+', '+age+', '+country+'

'+
  '// Nested
{ info: { title, level } }
→ '+title+', '+level+'

'+
  '// Function param
display(user) → '+display(user);