Learn about the Object data type in JavaScript, its usage for storing and manipulating key-value pairs, and how to create, access, and modify objects. Explore examples and code snippets to understand its versatility and role in JavaScript programming.
We will study: JavaScript Object Data Type, Object Literal, Object Constructor, Dot Notation, Square Bracket Notation, Creating Objects in JavaScript, Accessing Object Properties, Object Methods, Object-Oriented Programming in JavaScript.
step by step how to create object in javascript
Creating an object in JavaScript involves several steps. Let’s go through them step by step:
Step 1: Decide on the Object’s Structure
Before creating an object, you need to determine what data you want to store and how you want to organize it. Think about the properties and values that the object will hold.
Step 2: Choose an Object Creation Method
There are multiple ways to create an object in JavaScript.
The most common methods are using object literals ({}), the new Object() constructor, or creating a custom constructor function (ES5 and older).
Step 3: Define the Object’s Properties and Values
For an object literal, you can directly specify the properties and their values within curly braces {}. For constructor functions, you set properties using the this keyword within the function.
Step 4: Access and Modify Object Properties
After creating the object, you can access and modify its properties using dot notation (object.property) or square bracket notation (object[‘property’]).
Let’s put it all together in some code examples:
javascript
// Step 1: Decide on the object’s structure
// Step 1: Decide on the object's structure const person = { name: 'Omar', age: 30, isEmployed: true, hobbies: ['reading', 'cooking', 'traveling'], }; // Step 2: Object literal, directly define properties and values // Step 3: Object properties are already defined // Step 4: Accessing and modifying object properties document.write(person.name); // Output: "Omar" document.write(person.age); // Output: 30 person.isEmployed = false; document.write(person.isEmployed); // Output: false
javascript
// Step 1: Decide on the object’s structure (same as before)
// Step 2: Create the object using the constructor
// Step 1: Decide on the object's structure (same as before) // Step 2: Create the object using the constructor const person = new Object(); // Step 3: Define object properties person.name = 'Omar'; person.age = 30; person.isEmployed = true; person.hobbies = ['reading', 'cooking', 'traveling']; // Step 4: Accessing and modifying object properties (same as before) document.write(person.name); // Output: "Omar" document.write(person.age); // Output: 30 person.isEmployed = false; document.write(person.isEmployed); // Output: false
javascript
// Step 1: Decide on the object’s structure (same as before)
// Step 2: Create a constructor function
// Step 1: Decide on the object's structure (same as before) // Step 2: Create a constructor function function Person(name, age, isEmployed, hobbies) { this.name = name; this.age = age; this.isEmployed = isEmployed; this.hobbies = hobbies; } // Step 3: Create the object using the constructor function const person = new Person('Omar', 30, true, ['reading', 'cooking', 'traveling']); // Step 4: Accessing and modifying object properties (same as before) document.write(person.name); // Output: "Omar" document.write(person.age); // Output: 30 person.isEmployed = false; document.write(person.isEmployed); // Output: false
Those are the basic steps to create an object in JavaScript.
Choose the method that suits your needs, define the object’s properties, and you’ll have a flexible and powerful data structure to work with.
Examples
Here’s a basic example of creating an object:
javascript
// Creating an empty object const myObject = {}; // Creating an object with some key-value pairs const person = { name: 'Omar', age: 17, isEmployed: true, hobbies: ['reading', 'cooking', 'traveling'], address: { city: Cairo', zipCode: '10001', }, };
You can access the values of an object’s properties using either dot notation or square bracket notation:
javascript
document.write(person.name); // Output: "Omar" document.write(person['age']); // Output: 30 document.write(person.hobbies[0]); // Output: "reading" document.write(person.address.city); // Output: "Cairo"
complete code example in html
Here’s a complete HTML example that demonstrates creating an object in JavaScript using different methods (object literal, new Object() constructor, and custom constructor function):
<!DOCTYPE html> <html> <head> <title>Creating Objects in JavaScript</title> </head> <body> <h1>Creating Objects in JavaScript</h1> <script> // Using Object Literal const person1 = { name: 'Omar', age: 30, isEmployed: true, hobbies: ['reading', 'cooking', 'traveling'], }; // Using new Object() Constructor const person2 = new Object(); person2.name = 'Jane Smith'; person2.age = 25; person2.isEmployed = false; person2.hobbies = ['coding', 'gardening']; // Using Custom Constructor Function function Person(name, age, isEmployed, hobbies) { this.name = name; this.age = age; this.isEmployed = isEmployed; this.hobbies = hobbies; } const person3 = new Person('Alex Johnson', 28, true, ['swimming', 'painting']); // Displaying information on the page document.write('<h2>Using Object Literal:</h2>'); document.write(`<p>Name: ${person1.name}</p>`); document.write(`<p>Age: ${person1.age}</p>`); document.write(`<p>Is Employed: ${person1.isEmployed}</p>`); document.write(`<p>Hobbies: ${person1.hobbies.join(', ')}</p>`); document.write('<h2>Using new Object() Constructor:</h2>'); document.write(`<p>Name: ${person2.name}</p>`); document.write(`<p>Age: ${person2.age}</p>`); document.write(`<p>Is Employed: ${person2.isEmployed}</p>`); document.write(`<p>Hobbies: ${person2.hobbies.join(', ')}</p>`); document.write('<h2>Using Custom Constructor Function:</h2>'); document.write(`<p>Name: ${person3.name}</p>`); document.write(`<p>Age: ${person3.age}</p>`); document.write(`<p>Is Employed: ${person3.isEmployed}</p>`); document.write(`<p>Hobbies: ${person3.hobbies.join(', ')}</p>`); </script> </body> </html>
Explanation:
1-This example demonstrates how to create objects using an object literal, the new Object() constructor, and a custom constructor function (Person).
2-It defines properties for each object and displays their information on the web page using the document.write() method.
3-However, note that using document.write() directly in real-world applications is generally discouraged. Instead, you would typically use DOM manipulation to add content to the page dynamically.
To add or modify a property in an object, you can simply assign a value to it:
javascript
person.jobTitle = 'Software Engineer'; person.age = 31; document.write(person.jobTitle); // Output: "Software Engineer" document.write(person.age); // Output: 31
To delete a property from an object, you can use the delete keyword:
javascript
delete person.isEmployed; document.write(person.isEmployed); // Output: undefined
Objects can also have methods, which are functions stored as properties.
These methods can be used to perform actions or calculations related to the object’s data:
javascript
const calculator = { add: function (a, b) { return a + b; }, subtract: function (a, b) { return a - b; }, }; document.write(calculator.add(5, 3)); // Output: 8 document.write(calculator.subtract(10, 5)); // Output: 5
The Object data type is a crucial building block for more advanced data structures and plays a vital role in JavaScript programming.
complete code example in html
Here’s a complete HTML example that includes JavaScript code for creating an object and accessing its properties:
<!DOCTYPE html> <html> <head> <title>Object Example</title> </head> <body> <h1>JavaScript Object Example</h1> <script> // JavaScript code starts here const person = { name: 'Omar', age: 20, isEmployed: true, hobbies: ['reading', 'cooking', 'traveling'], address: { city: 'Cairo', zipCode: '1111', }, }; // Accessing properties of the person object const personName = person.name; const personAge = person['age']; const firstHobby = person.hobbies[0]; const cityName = person.address.city; // Adding a new property person.jobTitle = 'Software Engineer'; // Modifying an existing property person.age = 31; // Deleting a property delete person.isEmployed; // Displaying information on the page document.write(`<p>Name: ${personName}</p>`); document.write(`<p>Age: ${personAge}</p>`); document.write(`<p>First Hobby: ${firstHobby}</p>`); document.write(`<p>City: ${cityName}</p>`); document.write(`<p>Job Title: ${person.jobTitle}</p>`); </script> </body> </html>
Explanation:
1-In this example, we create the person object and access its properties using dot notation and square bracket notation.
2-We also add a new property (jobTitle) and modify the age property.
3-Finally, we delete the isEmployed property.
4-The results are displayed on the web page using the document.write() method. Note that document.write() is used for simplicity here, but it’s not recommended for real-world applications.
In practice, you’d use DOM manipulation to display content dynamically.
The Object data type in JavaScript is versatile and commonly used for various purposes. Below are some complete HTML examples demonstrating different use cases of the Object data type:
<!DOCTYPE html> <html> <head> <title>Object Example: Storing and Accessing Properties</title> </head> <body> <h1>JavaScript Object Example: Storing and Accessing Properties</h1> <script> // Creating an object const person = { name: 'Omar', age: 20, isEmployed: true, hobbies: ['reading', 'cooking', 'traveling'], address: { city: 'Cairo', zipCode: '1111', }, }; // Accessing properties document.write(`<p>Name: ${person.name}</p>`); document.write(`<p>Age: ${person.age}</p>`); document.write(`<p>Is Employed: ${person.isEmployed}</p>`); document.write(`<p>First Hobby: ${person.hobbies[0]}</p>`); document.write(`<p>City: ${person.address.city}</p>`); </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Object Example: Using Object Methods</title> </head> <body> <h1>JavaScript Object Example: Using Object Methods</h1> <script> const calculator = { add: function (a, b) { return a + b; }, subtract: function (a, b) { return a - b; }, }; // Using object methods const sum = calculator.add(5, 3); const difference = calculator.subtract(10, 5); // Displaying results document.write(`<p>Sum: ${sum}</p>`); document.write(`<p>Difference: ${difference}</p>`); </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Object Example: Looping Through Object Properties</title> </head> <body> <h1>JavaScript Object Example: Looping Through Object Properties</h1> <script> const car = { brand: 'Toyota', model: 'Camry', year: 2020, color: 'Blue', }; // Looping through object properties for (const key in car) { if (car.hasOwnProperty(key)) { const value = car[key]; document.write(`<p>${key}: ${value}</p>`); } } </script> </body> </html>
These examples illustrate some common use cases of the Object data type in JavaScript.
You can create objects, access their properties using dot notation or square bracket notation, use object methods for functionality, and loop through object properties for various purposes.
You can use objects to store configuration settings or options for your application:
<!DOCTYPE html> <html> <head> <title>Object Example: Configuration</title> </head> <body> <h1>JavaScript Object Example: Configuration</h1> <script> const config = { theme: 'dark', language: 'en', fontSize: 14, enableNotifications: true, }; // Using the configuration document.write(`<p>Theme: ${config.theme}</p>`); document.write(`<p>Language: ${config.language}</p>`); document.write(`<p>Font Size: ${config.fontSize}px</p>`); document.write(`<p>Notifications Enabled: ${config.enableNotifications}</p>`); </script> </body> </html>
Objects can be used as dictionaries, where keys represent words or identifiers, and values represent their meanings or associated data:
<!DOCTYPE html> <html> <head> <title>Object Example: Dictionary</title> </head> <body> <h1>JavaScript Object Example: Dictionary</h1> <script> const dictionary = { apple: 'a round fruit with red or green skin and a white inside', banana: 'a long curved fruit that grows in clusters', orange: 'a round fruit with a tough bright reddish-yellow rind', }; // Accessing dictionary values document.write(`<p>Meaning of "apple": ${dictionary.apple}</p>`); document.write(`<p>Meaning of "banana": ${dictionary.banana}</p>`); document.write(`<p>Meaning of "orange": ${dictionary.orange}</p>`); </script> </body> </html>
Objects can serve as data models to represent structured data, making it easy to organize and access data:
<!DOCTYPE html> <html> <head> <title>Object Example: Data Model</title> </head> <body> <h1>JavaScript Object Example: Data Model</h1> <script> const book = { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford', publicationYear: 2008, isbn: '978-0596517748', pages: 172, }; // Using data model properties document.write(`<p>Title: ${book.title}</p>`); document.write(`<p>Author: ${book.author}</p>`); document.write(`<p>Publication Year: ${book.publicationYear}</p>`); document.write(`<p>ISBN: ${book.isbn}</p>`); document.write(`<p>Number of Pages: ${book.pages}</p>`); </script> </body> </html>
Objects can be used to create modules, which are groups of related functions or methods:
<!DOCTYPE html> <html> <head> <title>Object Example: Modules</title> </head> <body> <h1>JavaScript Object Example: Modules</h1> <script> const mathUtils = { add: function (a, b) { return a + b; }, subtract: function (a, b) { return a - b; }, multiply: function (a, b) { return a * b; }, divide: function (a, b) { return a / b; }, }; // Using module functions const sum = mathUtils.add(5, 3); const difference = mathUtils.subtract(10, 5); document.write(`<p>Sum: ${sum}</p>`); document.write(`<p>Difference: ${difference}</p>`); </script> </body> </html>
Objects can be used to define event handlers or manage event-related information:
<!DOCTYPE html> <html> <head> <title>Object Example: Event Handlers</title> </head> <body> <h1>JavaScript Object Example: Event Handlers</h1> <script> const eventHandlers = { onClick: function (event) { alert('Button clicked!'); }, onMouseEnter: function (event) { event.target.style.backgroundColor = 'yellow'; }, onMouseLeave: function (event) { event.target.style.backgroundColor = 'white'; }, }; // Adding event handlers to an element const button = document.getElementById('myButton'); button.addEventListener('click', eventHandlers.onClick); button.addEventListener('mouseenter', eventHandlers.onMouseEnter); button.addEventListener('mouseleave', eventHandlers.onMouseLeave); </script> <button id="myButton">Click Me</button> </body> </html>
These examples showcase additional uses of the Object data type in JavaScript, including creating modules, passing options and callbacks to functions, managing event handlers, and more. Objects provide a flexible way to organize and structure data, making your code more maintainable and scalable.
1-What is the Object data type used for in JavaScript?
a) Storing only numbers
b) Storing and manipulating data in key-value pairs
c) Storing multiple values in an array
d) Storing text data only
Correct Answer: b) Storing and manipulating data in key-value pairs
2-How do you create an object in JavaScript using an object literal?
a) var obj = new Object();
b) var obj = { key: value };
c) var obj = [value];
d) var obj = { value };
Correct Answer: b) var obj = { key: value };
3-How do you access the value of a property in an object called person with the key “age”?
a) person[‘age’]
b) person.age
c) person[age]
d) person.property(‘age’)
Correct Answer: a) person[‘age’]
4-Which of the following statements is true about objects in JavaScript?
a) Objects can only store primitive data types.
b) Objects cannot contain functions as properties.
c) Objects are used to represent complex data structures and can hold various data types.
d) Objects can only have a fixed number of properties.
Correct Answer: c) Objects are used to represent complex data structures and can hold various data types.
5-How do you delete a property from an object called myObj with the key “name”?
a) delete myObj[name];
b) delete myObj.name;
c) myObj.deleteProperty(‘name’);
d) myObj.remove(‘name’);
Correct Answer: b) delete myObj.name;
6-Which of the following methods is used to add a new property to an existing object?
a) object.add(property, value);
b) object.createProperty(property, value);
c) object.addProperty(property, value);
d) object[property] = value;
Correct Answer: d) object[property] = value;
7-What is the difference between dot notation and square bracket notation when accessing object properties?
a) Dot notation is used for built-in properties, and square bracket notation is used for -defined properties.
b) Dot notation is used to access nested properties, and square bracket notation is used for top-level properties.
c) Dot notation is used for properties with simple names, and square bracket notation is used for properties with special characters or spaces.
d) There is no difference; both notations can be used interchangeably.
Correct Answer: c) Dot notation is used for properties with simple names, and square bracket notation is used for properties with special characters or spaces.
8-Which of the following is NOT a valid way to create an object in JavaScript?
a) Using an object literal: var obj = { key: value };
b) Using the Object() constructor: var obj = new Object();
c) Using an array: var obj = [value1, value2];
d) Using a custom constructor function: function MyObject() {} var obj = new MyObject();
Correct Answer: c) Using an array: var obj = [value1, value2];
9-What is the purpose of a constructor function in JavaScript?
a) To create new instances of objects with shared properties and methods.
b) To convert objects into primitive data types.
c) To define special methods that are only accessible from within the object.
d) To serialize objects into JSON format.
Correct Answer: a) To create new instances of objects with shared properties and methods.
10-Can objects in JavaScript have functions as their properties?
a) Yes, objects can have functions as their properties.
b) No, functions cannot be used as object properties.
c) Only built-in JavaScript objects can have functions as properties.
d) Yes, but only if the functions are declared inside the object using the function keyword.
Correct Answer: a) Yes, objects can have functions as their properties.
11-Which of the following methods can be used to check if a property exists in an object?
a) object.checkProperty(property);
b) object.exist(property);
c) object.hasProperty(property);
d) object.hasOwnProperty(property);
Correct Answer: d) object.hasOwnProperty(property);
12-What happens if you try to access a property that does not exist in an object?
a) The browser displays an error message.
b) The object automatically creates the property with a value of undefined.
c) JavaScript automatically creates the property with a value of null.
d) It returns undefined.
Correct Answer: d) It returns undefined.
13-What is the purpose of using square brackets ([]) in object literals?
a) To define an array inside the object.
b) To access properties with special characters or spaces.
c) To group related properties together.
d) There is no purpose for square brackets in object literals.
Correct Answer: b) To access properties with special characters or spaces.
14-Can objects in JavaScript be nested (i.e., contain other objects as their properties)?
a) No, objects cannot contain other objects as properties.
b) Yes, but only if the nested objects are created using the Object() constructor.
c) Yes, objects can contain other objects as properties, and this is called object nesting.
d) Yes, but only if the nested objects are created using the new keyword.
Correct Answer: c) Yes, objects can contain other objects as properties, and this is called object nesting.
15-Which statement correctly represents a key-value pair in an object?
a) key: value
b) value -> key
c) key => value
d) value : key
Correct Answer: a) key: value
رابط لشرح الدرس باللغة العربية من هنا
Mozilla Developer Network (MDN) Web Docs – Objects in JavaScript:
W3Schools – JavaScript Objects:
Eloquent JavaScript (Book) – Chapter 4: Data Structures: Objects and Arrays: