JavaScript Objects
Objects in JavaScript are collections of key-value pairs. They allow us to group related data and functionality together.
1️⃣ Creating an Object
Using Object Literal {}
(Most Common)
📌 You can access properties using dot notation
(object.property
) or bracket notation
(object["property"]
).
Using new Object()
(Less Common)
📌 The object literal {}
is preferred because it is simpler and more readable.
2️⃣ Nested Objects
Objects can contain other objects inside them.
3️⃣ Adding, Updating, and Deleting Properties
Add a New Property
Update a Property
Delete a Property
4️⃣ Methods in Objects (Functions as Properties)
Objects can have methods (functions inside objects).
📌 this
refers to the current object.
5️⃣ Object.keys(), Object.values(), Object.entries()
These methods help in working with object data.
6️⃣ Object Spread (...
) and Object.assign()
These are used to copy objects.
Using Spread (...
)
Using Object.assign()
7️⃣ Checking If a Property Exists
Use in
operator or hasOwnProperty()
.
8️⃣ Looping Over Object Properties
Use for...in
loop.
9️⃣ Object Freezing and Sealing
Prevent object modifications.
Freeze (No Changes Allowed)
Seal (Only Updates Allowed, No New Properties)
🔹 Summary
✅ Objects store data as key-value pairs
✅ Access properties → object.property
or object["property"]
✅ Nested objects → object.innerObject.property
✅ Methods (functions inside objects)
✅ Check property existence → "key" in object
or object.hasOwnProperty("key")
✅ Loop through objects → for...in
✅ Copy objects → Object.assign()
or { ...object }
✅ Freeze (Object.freeze()
) and Seal (Object.seal()
)
🚀 Now you're an object pro! Let me know if you have questions. 😊