𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
JavaScript objects store related data as key-value pairs. Each key acts as a unique identifier for its value.
Values in an object include:
- Primitives
- Other objects
- Functions (called methods)
Objects are mutable. You add, change, or remove properties at any time. This helps you group data and behavior together.
Two ways to create objects:
Object Literals Use curly braces to define properties directly. Example: const user = { name: "Vidhya", age: 23, job: "Developer" };
New Object Constructor Use the Object() constructor. Example: const user = new Object(); user.name = "Alex"; user.age = 4;
How to work with objects:
- Accessing data: Use dot notation (user.name) or bracket notation (user["name"]).
- Modifying data: Reassign a property value (user.age = 25).
- Adding data: Use dot or bracket notation to set a new key.
- Removing data: Use the delete operator.
- Checking properties: Use the "in" operator or hasOwnProperty() method.
- Looping: Use a for...in loop to go through all properties.
- Merging: Use Object.assign() or the spread syntax (...).
- Counting properties: Use Object.keys().
Always declare your objects with const to keep your references stable.
Source: https://dev.to/vidhya_murali_5aabe7784bd/objects-in-javascript-5600