𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
JavaScript objects store data in key-value pairs. Each pair is a property. The key is a string. The value is any data type like a number, string, or function.
You create objects using object literal notation. Use curly braces to hold your data.
Creating an object:
- Empty object: let empty = {};
- Object with data: let person = { firstName: 'John', lastName: 'Doe' };
You access properties in two ways:
Dot notation Use a period between the object name and the property name. Example: person.firstName
Array-like notation Use square brackets and quotes. This is necessary if your key has spaces. Example: address['building no']
Important rules:
- Using dots with property names containing spaces causes a syntax error.
- Avoid spaces in property names to prevent errors.
- If you try to read a property that does not exist, you get undefined.
You can change data inside an object:
- To update a value, use the assignment operator (=).
- To add a new property, assign a value to a new key.
- To remove a property, use the delete operator.
To check if a property exists, use the in operator. It returns true if the key is present and false if it is not.
Example: 'employeeId' in employee returns true.