Destructuring في JavaScript: السر وراء الكود الأنيق والقصير!
اليوم سنتعلم واحدة من أكثر الميزات أناقة وفائدة في JavaScript الحديثة (ES6+)، وهي Destructuring أو "التفكيك". إذا كنت تشعر أن كتابة كود لاستخراج القيم من الـ Arrays أو الـ Objects طويلة ومتكررة، فاستعد لتغيير رأيك!
Destructuring يسمح لك باستخراج قيم متعددة من الـ Arrays أو الـ Objects وتعيينها لمتغيرات جديدة، كل ذلك في سطر واحد من الكود. هذا يجعل الكود أكثر نظافة، قابلية للقراءة، وأقل عرضة للأخطاء.
لماذا نحتاج Destructuring؟ (المشكلة القديمة)
لنفهم الفائدة، دعنا نرى كيف كنا نستخرج القيم قبل وجود هذه الميزة.
مثال: استخراج قيم من Array بالطريقة التقليدية
// We have an array containing people's names
const people = ["Ahmed", "Sarah", "Khaled"];
// To extract each name into a separate variable, we used to write:
const firstPerson = people[0];
const secondPerson = people[1];
const thirdPerson = people[2];
console.log(firstPerson); // "Ahmed"
console.log(secondPerson); // "Sarah"
// Notice the repetition and long writing!
مثال: استخراج Properties من Object بالطريقة التقليدية
// We have an object representing user data
const user = {
name: "Noor",
age: 25,
city: "Riyadh"
};
// To extract properties, we used to write:
const userName = user.name;
const userAge = user.age;
const userCity = user.city;
console.log(userName); // "Noor"
// Again, repetitive and long code.
Destructuring يأتي لحل هذه المشكلة بشكل أنيق!
Destructuring الـ Arrays (Array Destructuring)
التفكيك يسمح لك بفك الـ Array وتعيين قيمها مباشرة لمتغيرات جديدة بناءً على موقعها (Index).
الصيغة الأساسية:
const [variable1, variable2, variable3] = array;
مثال عملي بسيط:
const colors = ["Red", "Green", "Blue"];
// Let's destructure the array!
const [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor); // "Red"
console.log(secondColor); // "Green"
console.log(thirdColor); // "Blue"
لاحظ كيف أصبح السطر الذي يستخرج القيم أقصر وأوضح!
تخطي العناصر (Skipping Items)
ماذا لو أردت العنصر الأول والثالث فقط وتخطي الثاني؟ الأمر سهل!
const numbers = [10, 20, 30, 40];
// Use a comma `,` to skip the position we don't want
const [firstNumber, , thirdNumber] = numbers;
console.log(firstNumber); // 10
console.log(thirdNumber); // 30 (Note that we skipped the element at index 1 which is 20)
القيمة الافتراضية (Default Values)
يمكنك تعيين قيمة افتراضية لمتغير في حالة كان الموضع المقابل في الـ Array غير محدد (undefined).
const fruits = ["Apple"];
// The array contains only one element
const [fruit1, fruit2 = "Banana"] = fruits; // Default value for fruit2
console.log(fruit1); // "Apple"
console.log(fruit2); // "Banana" (Default value used)
Destructuring الـ Objects (Object Destructuring)
التفكيك مع الـ Objects أكثر شيوعاً وفائدة! هنا نستخرج Properties بناءً على اسم المفتاح (Key Name) وليس الموضع.
الصيغة الأساسية:
const { property1, property2 } = object;
مثال عملي أساسي:
const student = {
fullName: "Fatima Ali",
grade: 95,
major: "Computer Science"
};
// Destructure the object to extract the desired properties
const { fullName, grade } = student;
console.log(fullName); // "Fatima Ali"
console.log(grade); // 95
// Note that we did not extract `major` because it was not mentioned.
تعيين أسماء متغيرات مختلفة (Aliasing)
ماذا لو أردت أن يكون اسم المتغير مختلفاً عن اسم Property في الـ Object؟ يمكنك ذلك بسهولة.
const car = {
brand: "Toyota",
model: "Camry",
year: 2022
};
// Extract the `brand` property but store its value in a variable named `company`
const { brand: company, model } = car;
console.log(company); // "Toyota" (value from `brand`)
console.log(model); // "Camry"
// console.log(brand); // Error! Variable `brand` is not defined.
القيم الافتراضية مع الـ Objects
كما في الـ Arrays، يمكنك تعيين قيم افتراضية للـ Properties التي قد تكون غير موجودة.
const settings = {
theme: "dark",
language: "en"
// `fontSize` property is missing
};
const { theme, language, fontSize = 16 } = settings;
console.log(fontSize); // 16 (default value because property is missing)
خلاصة وأمثلة واقعية بسيطة
لنجمع ما تعلمناه في أمثلة عملية صغيرة:
المثال ١: تبادل قيم متغيرين (Swap)
let a = 5;
let b = 10;
// Swap values using Destructuring (without a temporary variable!)
[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 5
المثال ٢: استقبال قيم من دالة
// Function that returns an array
function getCoordinates() {
return [24.7136, 46.6753]; // Latitude, Longitude
}
// Receive values directly into destructured variables
const [latitude, longitude] = getCoordinates();
console.log(`Latitude: ${latitude}`); // Latitude: 24.7136
اختبر معلوماتك
أسئلة قصيرة تتأكد بها من فهمك للدرس قبل أن تنتقل.
التعليقات
شاركنا رأيك أو أسئلتك حول هذا المحتوى