Now, let us store the details of a company employee using JavaScript object.
let names="Sam"
let employeeId = 1
let salary = 300000
JavaScriptWe have created three variables to store information about company employees, but if I want to add more details, I can use an array.
Now let us add some more details of the employee as follows.
let Userdetails = ["Sam",1,300000,22,"Bangalore"];
JavaScriptNow, if we observe the Userdetails array, we know that Sam is the name of the student. What is 22? Do we have any clarity regarding the number 22? Similarly “Bangalore”. Is “Bangalore” currently present or is it the place where he is from?
From the above example, I can say that storing information inside an array is not a good option.
To overcome this issue, we are having a data type → objects
Objects are also called key-value pairs. We can define the key which makes sense to the user and access its value. We can solve this Problem Using Objects. let’s see.
let Userdetails = {
name : "Sam", // name is key here and sam is value.
employeeId : 1,
salary : 300000,
age : 22, // age is key here and 22 is value.
Live : "Bangalore" // Live is key and Bangalore is value.
}
JavaScriptObject
What is an Object?
In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a property.
let obj = {
name : "Sam", // name is key here and sam is value.
age : 22, // age is key here and 22 is value.
Live : "Bangalore" // Live is key and Bangalore is value.
}
JavaScriptOne thing we have to keep in mind is that the keys that we provide for objects should be unique.
The value of properties or keys could be a string, number, boolean, object, an array , null, undefined, or a function.
const person = {
firstName: 'Anuj Singh',
lastName: 'Negi',
age: 22,
country: 'India',
city: 'New Delhi',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js'
],
isMarried: false
}
JavaScriptReal Life Use of Object
Like when we search for a mobile phone on Flipkart, it displays the available phones. However, it can be challenging to imagine how the data is stored behind the scenes and how it’s presented in the user interface. In reality, all the data is typically stored in the form of objects. Here’s an example:
const product = {
name: 'realme C51',
price: 8999,
description: 'A high-quality smartphone with advanced features.',
reviews: [
{
user: 'Priyanshu',
rating: 4,
comment: "I'm impressed with the performance of the realme C51."
},
{
user: 'Akhil',
rating: 5,
comment: "The realme C51 exceeded my expectations."
}
],
availability: true
}
JavaScriptGetting Values from an Object
How can I access the value of the Object?
We can access values of object using two methods:
- using “.” followed by key name if the key name is a one word
- using square bracket and a quote
Using Dot Notation: You can access a property of an object using the dot (.) notation by specifying the object’s name followed by the property name
const product = {
name: 'realme C51',
price: 8999,
description: 'A high-quality smartphone with advanced features.',
reviews: [
{
user: 'Priyanshu',
rating: 4,
comment: "I'm impressed with the performance of the realme C51."
},
{
user: 'Akhil',
rating: 5,
comment: "The realme C51 exceeded my expectations."
}
],
availability: true
}
const productName = product.name;
const productPrice = product.price;
const productDescription = product.description;
const review = product.reviews;
console.log("Product Name:", productName);
console.log("Product Price:", productPrice);
console.log("Product Description:", productDescription);
console.log("Product Review:" , review);
JavaScriptOutput:-
Product Name: realme C51
Product Price: 8999
Product Description: A high-quality smartphone with advanced features.
Product Review:[
{
user: 'Priyanshu',
rating: 4,
comment: "I'm impressed with the performance of the realme C51."
},
{
user: 'Akhil',
rating: 5,
comment: "The realme C51 exceeded my expectations."
}
]
JavaScriptUsing Bracket Notation:
You can also access object properties using bracket notation by specifying the object’s name followed by the property name inside square brackets.
const product = {
name: "realme C51",
price: 8,999,
description: "A high-quality smartphone with advanced features.",
reviews: [
{
user: 'Priyanshu',
rating: 4,
comment: "I'm impressed with the performance of the realme C51."
},
{
user: 'Akhil',
rating: 5,
comment: "The realme C51 exceeded my expectations."
}
],
availability: true
};
const productName = product['name'];
const productPrice = product['price'];
const productDescription = product['description'];
const review = product['reviews'];
console.log("Product Name:", productName);
console.log("Product Price:", productPrice);
console.log("Product Description:", productDescription);
console.log("Product Review:" , review);
JavaScriptOutput:-
Product Name: realme C51
Product Price: 8999
Product Description: A high-quality smartphone with advanced features.
Product Review:[
{
user: 'Priyanshu',
rating: 4,
comment: "I'm impressed with the performance of the realme C51."
},
{
user: 'Akhil',
rating: 5,
comment: "The realme C51 exceeded my expectations."
}
]
JavaScriptBoth dot notation and bracket notation can be used to get values from an object. Dot notation is commonly used when you know the property name in advance, while bracket notation is useful when the property name is dynamic or when it contains special characters (e.g., spaces or hyphens).
Insertion in Object in JavaScript
Suppose I want to add new properties in our Object . let’s see how to do that?
Insertion in the context of objects refers to adding new properties and their values to an existing object. You can do this using the assignment operator (=) and specifying the new property name and value. Here’s how you can insert a new property into an object
const product = {
name: "realme C51",
price: 8999,
description: "A high-quality smartphone with advanced features.",
reviews: [],
availability: true
};
// Insert a new property "manufacturer" with a value
product.manufacturer = "XYZ Corp";
console.log(product);
JavaScriptOutput
{
name: "realme C51",
price: 8999,
description: "A high-quality smartphone with advanced features.",
reviews: [],
availability: true,
manufacturer: "XYZ Corp"
}
JavaScriptUpdation in an Object in JavaScript
Suppose You want to change the properties of your object. let’s see how to do that.
Updating an object involves changing the value of an existing property within the object. To update a property’s value, you can simply reassign the property with the new value. Here’s how you can update a property in an object:
const product = {
name: "realme C51",
price: 8999,
description: "A high-quality smartphone with advanced features.",
reviews: [],
availability: true
};
// Update the "price" property with a new value
product.price = 12000;
console.log(product);
JavaScriptOutput
{
"name": "realme C51",
"price": 12000,
"description": "A high-quality smartphone with advanced features.",
"reviews": [],
"availability": true
}
JavaScriptDelete in an Object in JavaScript
Suppose if i want to delete any properties from an object ? let’s see how to do that?
Deleting a property from an object involves removing a specific property and its associated value from the object. You can use the delete keyword followed by the object’s name and the property you want to delete. Here’s how you can delete a property from an object
const product = {
name: "realme C51",
price: 12000,
description: "A high-quality smartphone with advanced features.",
reviews: [],
availability: true
};
// Delete the "availability" property
delete product.availability;
console.log(product);
JavaScriptOutput
{
"name": "realme C51",
"price": 12000,
"description": "A high-quality smartphone with advanced features.",
"reviews": []
}
JavaScriptIterating Over Object
You can iterate over the properties of an object in JavaScript using a for…in loop. Here’s how you can iterate over the properties of the product object .
const product = {
name: "realme C51",
price: 12000,
description: "A high-quality smartphone with advanced features.",
reviews: [],
availability: true
};
for (const key in product) {
console.log(key + ": " + product[key]);
}
JavaScriptOutput
name: realme C51
price: 12000
description: A high-quality smartphone with advanced features.
reviews:
availability: true
JavaScriptConclusion
JavaScript objects are powerful data structures that allow you to store and manage data in key-value pairs. They provide a flexible way to organize your data and are essential for creating more complex and structured JavaScript applications. By understanding how to create, access, modify, and iterate over objects, you can effectively manage and utilize your data in a variety of programming scenarios. Whether you’re building web applications, managing state, or simply organizing data, mastering JavaScript objects is a crucial step in becoming proficient in JavaScript.
Frequently Asked Questions
Ans: A JavaScript object is an unordered collection of key-value pairs, where each key (also called a property) is unique and associated with a value. Values can be of any type, including other objects, functions, and arrays.
Q2. How do you create an object in JavaScript?
You can create an object using curly braces {}
, with key-value pairs inside. Keys are strings, and values can be any data type.const person = {
name: "John Doe",
age: 30
};
Q3. How can you access the properties of an object?
Ans: You can access object properties using dot notation or bracket notation.
Dot Notation: objectName.propertyName
Bracket Notation: objectName["propertyName"]
Q4. How do you add new properties to an object?
Ans: You can add a new property to an object by simply assigning a value to a new key using either dot notation or bracket notation.const person = {
name: "John Doe"
};
person.age = 30; // Using dot notation
person["city"] = "New York"; // Using bracket notation
Ans: Iterating over an object allows you to access each property and its value, which is useful for tasks such as displaying all the information contained in the object or processing each property individually.