An Object is an Unordered Collection of PropertiesProperties are a key component of JavaScript objects. They can be modified, added, removed, and some may be read-only. |
The syntax for accessing an object’s property is:
| // objectName.property let age = person.age; |
or
| //objectName[“property“] let age = person[“age”]; |
or
| //objectName[expression] let age = person[x]; |
Example
| person.firstname + ” is “ + person.age + ” years old.”; |
| person[“firstname”] + ” is “ + person[“age”] + ” years old.”; |
| person[“firstname”] + ” is “ + person[“age”] + ” years old.”; |
You can add new properties to an existing object by assigning them a value.
Example
| person.nationality = “English”; |
The delete keyword removes a property from an object:
Example
| const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; delete person.age; |
Alternatively, `delete person[“age”];
Example
| const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; delete person[“age”]; |
|
NOTE: |
Values of properties in an object can themselves be other objects.
Example
| myObj = { name:“John”, age:30, myCars: { car1:“Ford”, car2:“BMW”, car3:“Fiat” } } |
Nested objects can be accessed using either the dot notation or the bracket notation.
Examples
| myObj.myCars.car2; |
| myObj.myCars[“car2”]; |
| myObj[“myCars”][“car2”]; |
| let p1 = “myCars”; let p2 = “car2”; myObj[p1][p2]; |