Destructuring

Destructuring یعنی استخراج مقادیر از آرایه‌ها یا آبجکت‌ها و اختصاص دادن اون‌ها به متغیرها به‌صورت ساده‌تر و خواناتر.

📌 1. تخریب‌سازی آرایه‌ها (Array Destructuring)

const numbers = [10, 20, 30]; // به‌جای این: const a = numbers[0]; const b = numbers[1]; // این‌طوری: const [x, y, z] = numbers; console.log(x); // 10 console.log(y); // 20 console.log(z); // 30

🔹 می‌تونی بعضی مقادیر رو نگیری:

const [first, , third] = [1, 2, 3]; console.log(first, third); // 1, 3

🔹 مقدار پیش‌فرض:

const [a = 5, b = 10] = [7]; console.log(a, b); // 7, 10

📌 2. تخریب‌سازی آبجکت‌ها (Object Destructuring)

const person = { name: "Ali", age: 25, city: "Tehran" }; const { name, age } = person; console.log(name); // Ali console.log(age); // 25

🔹 تغییر نام متغیرها:

const { name: fullName, city: location } = person; console.log(fullName); // Ali console.log(location); // Tehran

🔹 مقدار پیش‌فرض:

const { job = "Developer" } = person; console.log(job); // Developer

📌 3. استفاده در توابع

function printUser({ name, age }) { console.log(`${name} is ${age} years old`); } printUser({ name: "Sara", age: 30 }); // Sara is 30 years old

📌 4. تخریب‌سازی تو در تو (Nested Destructuring)

const user = { id: 1, profile: { username: "coder", email: "coder@example.com" } }; const { profile: { username, email } } = user; console.log(username); // coder console.log(email); // coder@example.com

📌 5. ترکیب با Rest Operator (...)

const [first, ...rest] = [10, 20, 30, 40]; console.log(first); // 10 console.log(rest); // [20, 30, 40] const { name, ...others } = { name: "Ali", age: 25, city: "Tehran" }; console.log(name); // Ali console.log(others); // { age: 25, city: "Tehran" }

✅ تخریب‌سازی خیلی پرکاربرده، مخصوصاً توی React, Vue, Node.js برای گرفتن داده‌ها از props، API یا query string.