𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
JavaScript objects store data in key-value pairs. You call each pair a property.
A key is a string. A value is anything. It is a string, a number, an array, or a function.
Creating Objects
You use object literal notation to make an object. Use curly braces to define it.
An empty object: let empty = {};
An object with properties: let person = { firstName: 'John', lastName: 'Doe' };
Accessing Properties
You use two methods to get data from an object.
Dot notation Use a dot followed by the property name. person.firstName
Array-like notation Use square brackets and quotes. This is necessary if your property name has spaces. person['firstName']
Example with spaces: let address = { 'building no': 3960 }; address['building no']
Note: Avoid spaces in property names to prevent errors.
Managing Properties
You can change, add, or remove data at any time.
Modify a value: person.firstName = 'Jane';
Add a new property: person.age = 25;
Delete a property: delete person.age;
If you try to access a property that does not exist, JavaScript returns undefined.
Check if a property exists
Use the in operator to check for a key. It returns true or false.
'employeeId' in employee
This tells you if the key lives inside the object.