FacebookTwitterLinkedIn

English translation by ChatGPT

Ahmed Zayed 9/2/1/1 أساسيات الجافاسكريبت 'الـ Objects'Ahmed Zayed 9/2/1/1 أساسيات الجافاسكريبت 'الـ Objects'

Course

دورة تدريبية

9/2/1/1 أساسيات الجافاسكريبت 'الـ Objects'

تطوير المواقع الإلكترونية MEAN-Stack from A to Z الأساسيات Level1

يمكن إعتبار الـ object علي أنه إستحداث datatype جديد properties و methods جديدة, فمثلا لو كنا نريد التعامل مع بيانات تلاميذ فهناك بعض الخصائص المشتركة للتلاميذ و أيضا هناك بعض الـ methods التي تطبق عليها , مثلا لكل تلميذ هناك الاسم , العمر, العنوان, رقم الصف فهل من المنطقي أن نقوم بعمل متغيرات لكل هذه الصفات و لكل تلميذ مثلا
Code

          let student1Nmae = "Ahmed Zayed";
          let student1Age= 10;
          let student1Address='Cairo';
          let student1GradeNO = '4';
      
و عمل متغير لكل تلميذ بالطبع لا يمكن القيام بذلك و بدلا من ذلك يتم عمل object للتلميذ, مثل الكود التالي:
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4
         }
         console.log(student.name);
         console.log(student['name']);
      
و هكذا بكل بساطة أصبحنا نمتلك object واحد يحتوي علي كل بيانات الطالب أيضا يمكننا الوصول لبيانات الطالب من خلال كتابة اسم الـ object و بعده نقطة ثم اسم الخاصية او ما يعرف بـ dot notation أو كتابتها بين أقواس أو ما يعرف بـ bracket notation [‘اسم الخاصية’] مثل في المثال السابق ['name'] .
أيضا يمكننا زيادة أي خاصية فيما بعد مثل:
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4
         }
        student.id=5;
        console.log(student.id);
      
أيضا يمكننا كتابة function بداخل الـ object مثل :
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4,
            SayHello:function(){
                return 'hello student'
            }
         }
         console.log(student.SayHello());
      
و يمكن للـ method أن تتعامل مع خصائص الـ Object مثل
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4,
            SayHello:function(){
                return 'hello ' + student.name
            }
         }
         console.log(student.SayHello());
      
و لكن استخدام student.name بداخل الـ function الموجودة بداخل الـ object ليس أفضل الممارسات لان بيانات الـ object متغيرة و قد تنتقل لـ object أخر كما سنري بعد قليل و لذلك يجب أن نستخدم عوضا عنها كلمة this و كلمة this تشير إلي الـ object الذي ينتمي إليه الكود سنعرف عن طريق المثال التالي عندما نقوم بعمل Object من Object أخر عن طريق Create كمثال بالكود التالي:
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4,
            SayHello:function(){
                return 'hello ' + student.name
            }
         }
         let student2 = Object.create(student);
         student2.name = 'omar';
         console.log(student2.name);
         console.log(student2.SayHello());
      
في الكود السابق قمنا بنسخ الـ object المسمي student و عمل object جديد اسمه student2 و قمنا بتغيير الاسم لـ omar و عند طباعة الإسم علي الكونسول نجد أنه يطبع omar بدون مشاكل و لكن عند استدعاء الـ method المسماه SayHello يتم طباعة hello Ahmed Zayed حتي بعد تغيير الإسم لاننا استخدمنا في الـ method كلمة student.name لو قمنا بتغيير الكود كما في الكود التالي:
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4,
            SayHello:function(){
                return 'hello ' + this.name
            }
         }
         let student2 = Object.create(student);
         student2.name = 'omar';
         console.log(student2.name);
         console.log(student2.SayHello());
      
هكذا سوف تكتب hello omar فكلمة this تقوم بالإشارة للـ object الحالي أيضا يمكننا زيادة خصائص الـ object أثناء إنشاءه عن طريق create هكذا
Code

          let student={
            name:'Ahmed Zayed',
            age:10,
            address:'cairo',
            gradeNo:4,
            SayHello:function(){
                return 'hello ' + this.name
            }
         }
         let student2 = Object.create(student,{
            isActive:{value:true},
            gender:{value:'male'}});
         console.log(student2);
      
يمكن أن يحتوي الـ object علي objects أخري أو arrays أو أي شيء أيضا يمكن صنع object من مجموعة من الـ objects مثل
Code

          let o1={p1:1}
          let o2={p2:2}
          let o3={p3:3}
          let o4=Object.assign(o1,o2,o3);
          console.log(o4);
      
- تجميد عناصر الـ Object أي جعلها غير قابلة للتعديل و التغيير عن طريق freeze مثل الكود التالي:
Code

          const frozenObject = Object.freeze({ name: 'Frozen' });
          frozenObject.name = 'New Name'; // This will not work
          console.log(frozenObject.name); // Output: Frozen
      
و تتيح تلك الخاصية إنشاء Object جديد غير قابل للتعديل عليه و هي خاصية مفيدة للحفاظ على القيم المسجلة داخل Object ما من التعديل أو الحذف أو الإضافة. - استخدام الخاصية seal لمنع إضافة عناصر جديدة للـ object و لكن يمكن التعديل على العناصر الجديدة مثل:
Code

          const sealedObject = Object.seal({ name: 'Sealed' });
          sealedObject.newProp = 'new'; // This will not work
          sealedObject.name = 'Updated Name'; // This works
          console.log(sealedObject.name); // Output: Updated Name
      
- استخدام الـ Dynamic Property Names اي أن المتغيرات الخاصة بالـ Object من الممكن أن تسمى بأسماء متغيرة يمكن تحديدها برمجيا مثل:
Code

          const propName = 'dynamicProp';
          const obj = {
            [propName]: 'My Value'
          };
          console.log(obj.dynamicProp); // Output: My Value
      
و من الممكن أستخدام تلك الخاصية في الحياة العملية مثل:
Code

          const prefix = 'user_';
          const userId = 123;
          const user = {
            [`${prefix}${userId}`]: 'Ali'
          };
          console.log(user['user_123']); // Output: Ali
      

الـ Destructuring

و هى خاصية هامة في الجافاسكريبت كما ذكرنا من قبل في الـ arrays يمكن استخدامها أيضا مع الـ object و هي ببساطة تعيين متغيرات جديدة من Object موجود مثل:
Code

          const user = { name: 'Ali', age: 25 };
          const { name, age } = user;
          console.log(name); // Output: Ali
          console.log(age);  // Output: 25
      
و يمكن أيضا تغيير أسماء المتغيرات عن اسماء الـ properties الخاصة بالـ object مثل:
Code

          const user = { name: 'Ali', age: 25 };
          const { name: userName, age: userAge } = user;
          console.log(userName); // Output: Ali
          console.log(userAge);  // Output: 25
      
استخدام القيم الإفتراضية للمتغيرات الجديدة
Code

          const user = { name: 'Ali' };
          const { name, age = 30 } = user;
          console.log(name); // Output: Ali
          console.log(age);  // Output: 30 (default value)
      
في الكود السابق لا يوجد خاصية بإسم age في الـ object لذلك يعرض القيمة الإقتراضية بينما في حالة وجود خاصية بنفس الاسم فسيعرض القيمة الفعلية للخاصية مثل:
Code

          const user = { name: 'Ali',age:25 };
          const { name, age = 30 } = user;
          console.log(name); // Output: Ali
          console.log(age);  // Output: 25
      
ايضا يمكن تطبيق الـ Destructuring مع الـ objects المتداخلة (nested objects) مثل:
Code

          const user = {
            name: 'Ali',
            address: {
              city: 'Cairo',
              zip: '12345'
            }
          };
          const { address: { city, zip } } = user;
          console.log(city); // Output: Cairo
          console.log(zip);  // Output: 12345
      
أيضا يمكن استخدام الـ Destructuring لتمرير الـ function arguments مثل
Code

          function greet({ name, age }) {
            console.log(`Hello, my name is ${name} and I am ${age} years old.`);
          }
          const user = { name: 'Ali', age: 25 };
          greet(user); // Output: Hello, my name is Ali and I am 25 years old.
      
أو يمكن استخدامه بهذه الطريقة
Code

          function greet(user) {
            const {name,age} = user;
            console.log(`Hello, my name is ${name} and I am ${age} years old.`);
          }
          const user = { name: 'Ali', age: 25 };
          greet(user); // Output: Hello, my name is Ali and I am 25 years old.
      
الـ Destructuring مع الـ loop عندما يكون هناك array بها عدد من الـ objects يمكن عمل loop على الـ array و تطبيق الـ Destructuring على كل object مثل:
Code

          const users = [
          { name: 'Ali', age: 25 },
          { name: 'Omr', age: 30 }
        ];
        for (const { name, age } of users) {
          console.log(`${name} is ${age} years old.`);
        }
        // Output:
        // Ali is 25 years old.
        // Omr is 30 years old.
      

الـ Spread Syntax

كما في الـ array يمكن استخدامها في العديد من الحالات للتعامل مع الـ Objects مثل: إنشاء object جديد من object قديم مثل الكود التالي:
Code

         
          const original = { a: 1, b: 2 };
          const copy = { ...original };
          console.log(copy); // Output: { a: 1, b: 2 }
          console.log(copy === original); // Output: false (different references)
      
و يلاحظ في الكود السابق أن الـ Object الجديد منفصل عن الـ object مما يعني ان أي تعديل على أحدهما لن يؤثر على الأخر مثل:
Code

          const original = { a: 1, b: 2 };
          const copy = { ...original };
          copy.a=10;
          console.log(copy); // Output: { a: 10, b: 2 }
          console.log(original); // Output: { a: 1, b: 2 }
      
بينما الكود التالي ينتج عنه ربطهما معا و أي تغيير في احدهما يؤثر على الأخر
Code

          const original = { a: 1, b: 2 };
          const copy = original;
          copy.a=10;
          console.log(copy); // Output: { a: 10, b: 2 }
          console.log(original); // Output: { a: 10, b: 2 }
      
إنشاء object عن طريق دمج أكثر من object معا مثلا:
Code

          const obj1 = { a: 1, b: 2 };
          const obj2 = { b: 3, c: 4 };
          const merged = { ...obj1, ...obj2 };
          console.log(merged); // Output: { a: 1, b: 3, c: 4 }
      
إنشاء Object عن طريق دمج خصائص Object أخر مع بعض الخصائص الأخرى مثل:
Code

          const user = { name: 'Ali', age: 25 };
          const updatedUser = { ...user, age: 26,city:'Cairo' };
          console.log(updatedUser); // Output: { name: 'Ali', age: 26 }
          console.log(user); // Output: { name: 'Ali', age: 25 } (original object remains unchanged)
      
أيضا يمكن إستخدام جملة شرطية condition مثل:
Code

          const condition = true;
          const base = { a: 1, b: 2 };
          const conditionalProps = condition ? { b: 3, c: 4 } : { b: 2, d: 5 };
          const result = { ...base, ...conditionalProps };
          console.log(result); // Output: { a: 1, b: 3, c: 4 }
      
دمج الـ spread syntax مع الـ destructuring
Code

          const user = { name: 'Ali', age: 25, location: 'Cairo' };
          const { name, ...details } = user;
          console.log(name);    // Output: Ali
          console.log(details); // Output: { age: 25, location: 'Cairo' }
      
استخدام القيم الإفتراضية Default Values
Code

          function createConfig(userConfig) {
            const defaultConfig = { timeout: 5000, retries: 3 };
            return { ...defaultConfig, ...userConfig };
          }
          const config = createConfig({ retries: 5, verbose: true });
          console.log(config); // Output: { timeout: 5000, retries: 5, verbose: true }
      
الجدير بالذكر أن الـ spread syntax عملية مكلفة إلى حد كبير عند التعامل مع الذاكرة و سرعة التطبيق و الأداء لذلك يجب التعامل معها بحذر و إستخدامها عند الحاجة خصوصا عند التعامل مع البيانات كبيرة الحجم لانها تقوم بإنشاء objects جديدة في الذاكرة و هو ما سنستعرضه لاحقا.
في الحقيقة الـ objects هي أساس كل التطبيقات الحديثة و طرق البرمجة المتبعة حاليا و شرحها و إستخدامتها متعددة جدا و لكن هذه نبذة كافية الأن عن الـ objects حتى درس الـ OOP (Object Oriented Programming)

1/1/2/9 JavaScript fundamentals: 'Objects'

Website Development MEAN-Stack from A to Z Fundamentals Level1

An object can be considered as a new datatype with new properties and methods. For example, if we want to deal with student data, there are some common properties for students and also some methods that can be applied to them. For instance, each student has a name, age, address, and grade number. Is it logical to create variables for each of these attributes for each student?
Code

                let student1Nmae = "Ahmed Zayed";
                let student1Age= 10;
                let student1Address='Cairo';
                let student1GradeNO = '4';
            
Creating a variable for each student is, of course, not feasible. Instead, we can create an object for the student, as shown in the following code:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4
               }
               console.log(student.name);
               console.log(student['name']);
            
And just like that, we now have a single object that contains all the student's data. We can also access the student's data by writing the object's name followed by a dot and then the property name, known as dot notation, or by using brackets, known as bracket notation ['property name'], as shown in the previous example ['name'].
We can also add any property later, like this:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4
               }
              student.id=5;
              console.log(student.id);
            
We can also write a function inside the object, like this:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4,
                  SayHello:function(){
                      return 'hello student'
                  }
               }
               console.log(student.SayHello());
            
The method can also interact with the object's properties, like this:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4,
                  SayHello:function(){
                      return 'hello ' + student.name
                  }
               }
               console.log(student.SayHello());
            
However, using `student.name` inside the function within the object is not the best practice because the object's data can change, and it might be transferred to another object, as we will see shortly. Instead, we should use the keyword `this`. The keyword `this` refers to the object to which the code belongs. We will understand this through the following example when we create an object from another object using `Create`, as shown in the following code:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4,
                  SayHello:function(){
                      return 'hello ' + student.name
                  }
               }
               let student2 = Object.create(student);
               student2.name = 'omar';
               console.log(student2.name);
               console.log(student2.SayHello());
            
In the previous code, we copied the object named `student` and created a new object named `student2`. We changed the name to `omar`, and when we printed the name to the console, it printed `omar` without any issues. However, when we called the method `SayHello`, it printed `hello Ahmed Zayed` even after changing the name because we used `student.name` in the method. If we change the code as shown in the following code:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4,
                  SayHello:function(){
                      return 'hello ' + this.name
                  }
               }
               let student2 = Object.create(student);
               student2.name = 'omar';
               console.log(student2.name);
               console.log(student2.SayHello());
            
Now it will print `hello omar`. The keyword `this` refers to the current object. We can also add properties to the object during its creation using `create`, like this:
Code

                let student={
                  name:'Ahmed Zayed',
                  age:10,
                  address:'cairo',
                  gradeNo:4,
                  SayHello:function(){
                      return 'hello ' + this.name
                  }
               }
               let student2 = Object.create(student,{
                  isActive:{value:true},
                  gender:{value:'male'}});
               console.log(student2);
            
An object can contain other objects, arrays, or anything else. We can also create an object from a group of objects, like this:
Code

                let o1={p1:1}
                let o2={p2:2}
                let o3={p3:3}
                let o4=Object.assign(o1,o2,o3);
                console.log(o4);
            
- Freezing object elements to make them unmodifiable using `freeze`, as shown in the following code:
Code

                const frozenObject = Object.freeze({ name: 'Frozen' });
                frozenObject.name = 'New Name'; // This will not work
                console.log(frozenObject.name); // Output: Frozen
            
This feature allows the creation of a new object that cannot be modified, which is useful for preserving the values stored inside an object from being changed, deleted, or added. - Using the `seal` property to prevent adding new elements to the object, but allowing modification of existing elements, like this:
Code

                const sealedObject = Object.seal({ name: 'Sealed' });
                sealedObject.newProp = 'new'; // This will not work
                sealedObject.name = 'Updated Name'; // This works
                console.log(sealedObject.name); // Output: Updated Name
            
- Using Dynamic Property Names, meaning that the object's properties can be named with variable names that can be determined programmatically, like this:
Code

                const propName = 'dynamicProp';
                const obj = {
                  [propName]: 'My Value'
                };
                console.log(obj.dynamicProp); // Output: My Value
            
This feature can be used in real-life scenarios, like this:
Code

                const prefix = 'user_';
                const userId = 123;
                const user = {
                  [`${prefix}${userId}`]: 'Ali'
                };
                console.log(user['user_123']); // Output: Ali
            

Destructuring

This is an important feature in JavaScript, as mentioned before with arrays. It can also be used with objects. It simply assigns new variables from an existing object, like this:
Code

                const user = { name: 'Ali', age: 25 };
                const { name, age } = user;
                console.log(name); // Output: Ali
                console.log(age);  // Output: 25
            
We can also change the variable names from the object's property names, like this:
Code

                const user = { name: 'Ali', age: 25 };
                const { name: userName, age: userAge } = user;
                console.log(userName); // Output: Ali
                console.log(userAge);  // Output: 25
            
Using default values for new variables:
Code

                const user = { name: 'Ali' };
                const { name, age = 30 } = user;
                console.log(name); // Output: Ali
                console.log(age);  // Output: 30 (default value)
            
In the previous code, there is no property named `age` in the object, so it displays the default value. However, if a property with the same name exists, it will display the actual value of the property, like this:
Code

                const user = { name: 'Ali',age:25 };
                const { name, age = 30 } = user;
                console.log(name); // Output: Ali
                console.log(age);  // Output: 25
            
Destructuring can also be applied to nested objects, like this:
Code

                const user = {
                  name: 'Ali',
                  address: {
                    city: 'Cairo',
                    zip: '12345'
                  }
                };
                const { address: { city, zip } } = user;
                console.log(city); // Output: Cairo
                console.log(zip);  // Output: 12345
            
Destructuring can also be used to pass function arguments, like this:
Code

                function greet({ name, age }) {
                  console.log(`Hello, my name is ${name} and I am ${age} years old.`);
                }
                const user = { name: 'Ali', age: 25 };
                greet(user); // Output: Hello, my name is Ali and I am 25 years old.
            
Or it can be used this way:
Code

                function greet(user) {
                  const {name,age} = user;
                  console.log(`Hello, my name is ${name} and I am ${age} years old.`);
                }
                const user = { name: 'Ali', age: 25 };
                greet(user); // Output: Hello, my name is Ali and I am 25 years old.
            
Destructuring with loops when there is an array containing multiple objects. We can loop through the array and apply destructuring to each object, like this:
Code

                const users = [
                { name: 'Ali', age: 25 },
                { name: 'Omr', age: 30 }
              ];
              for (const { name, age } of users) {
                console.log(`${name} is ${age} years old.`);
              }
              // Output:
              // Ali is 25 years old.
              // Omr is 30 years old.
            

Spread Syntax

As with arrays, it can be used in many cases to deal with objects, like: Creating a new object from an old one, as shown in the following code:
Code

               
                const original = { a: 1, b: 2 };
                const copy = { ...original };
                console.log(copy); // Output: { a: 1, b: 2 }
                console.log(copy === original); // Output: false (different references)
            
Notice in the previous code that the new object is separate from the original object, meaning that any modification to one will not affect the other, like this: Combining spread syntax with destructuring
Code

  const user = { name: 'Ali', age: 25, location: 'Cairo' };
  const { name, ...details } = user;
  console.log(name);    // Output: Ali
  console.log(details); // Output: { age: 25, location: 'Cairo' }
Using Default Values
Code

  function createConfig(userConfig) {
    const defaultConfig = { timeout: 5000, retries: 3 };
    return { ...defaultConfig, ...userConfig };
  }
  const config = createConfig({ retries: 5, verbose: true });
  console.log(config); // Output: { timeout: 5000, retries: 5, verbose: true }
It is worth noting that the spread syntax is quite costly in terms of memory usage, application speed, and performance. Therefore, it should be used with caution and only when necessary, especially when dealing with large data sets, as it creates new objects in memory, which we will discuss later.
In fact, objects are the foundation of all modern applications and current programming practices. Their explanation and usage are very diverse, but this is a sufficient overview of objects for now until the OOP (Object-Oriented Programming) lesson.

February 28, 2025

Read More
إقرأ المزيد

التسويق الرقمي و الأهداف غير الواقعية

Digital Marketing and Unrealistic Goals

دورة تدريبية

Course

5/2/1/1 أساسيات الجافاسكريبت 'الجمل الشرطية Conditional statements'

1/1/2/5 JavaScript fundamentals 'Conditional Statements'

صناعة التطبيقات و وهم الثراء السريع

The App Industry and the Illusion of Quick Wealth

التسويق الرقمي في المؤسسات الحكومية

Digital Marketing in Government Institutions

دورة تدريبية

Course

8/2/1/1 أساسيات الجافاسكريبت 'الـ Arrays'

1/1/2/8 JavaScript fundamentals 'Arrays'

Keywords
كلمات مفتاحية

mean-stack دورة الـ دورة الـ mean-stack from a to z دورة النود بالعربي دورة تطوير المواقع الإلكترونية دورة الأنجولر بالعربي

mean-stack coursecourse mean-stack from a to zcourse mean-stack from a to znode js arabic courseweb development courseangular arabic course

© 2026 Ahmed Zayed. All rights reserved.© 2026 كل الحقوق محفوظة أحمد زايد