𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱
JavaScript objects store data in key-value pairs. Each pair is a property.
A property holds different types of data:
- Strings
- Numbers
- Arrays
- Other objects
- Functions
When a function lives inside an object, it is called a method. Methods define what an object does.
Example: const human = { firstName: "Virat", lastName: "Kohli", age: 30, fullName: function() { return this.firstName + " " + this.lastName } }
In this example, firstName is a key and "Virat" is the value.
Ways to create objects:
Object Literals Use curly braces to define properties directly. let user = { name: "Sourav", age: 23 };
Object Constructor Use the new Object() syntax. let user = new Object(); user.name = "Sourav";
How to access properties:
- Dot notation: user.name
- Bracket notation: user["name"]
You can change objects after you create them. You can add new properties or remove existing ones.
To remove a property, use the delete operator: delete user.age;
To check if a property exists, use the in operator or hasOwnProperty: "name" in user; user.hasOwnProperty("name");
Objects help you group related data and behavior in one place. This makes your code organized and easy to manage.
Source: https://dev.to/kamalesh_ar_6252544786997/objects-in-javascript-2kc9