Loading lesson path
Concept visual
Start at both ends
A
Properties can be changed, added, and deleted.
You can access object properties in these ways:
//
objectName.property let age = person.age;// objectName [" property "]
let age = person["age"];// objectName [ expression ]
let age = person[x];
Dot Notation objectName.propertyName person.firstname + " is " + person.age;
Bracket Notation objectName["propertyName"]
person["firstname"] + " is " + person["age"];In general, dot notation is preferred for readability and simplicity. Bracket notation is necessary in some cases: The property name is stored in a variable: person[myVariable] The property name is not a valid identifier:
Formula
person["last - name"]Bracket notation is useful when the property name is stored in a variable:
let n1 = "firstName";
let n2 = "lastName";
let name = person[n2] + " " + person[n2];You can change the value of a property:
Example person.age = 10;You can add a new property by simply giving it a value:
Example person.nationality = "English";The delete keyword deletes a property from an object:
Examples const person = {
firstName: "John", lastName: "Doe", age: 50,
};
delete person.age;
const person = {
firstName: "John", lastName: "Doe", age: 50,
};
delete person["age"];The delete keyword deletes both the value and the property.
After deleting, the property is removed. Accessing it will return undefined.Use the in operator to check if a property exists in an object:
const person = {
firstName: "John", lastName: "Doe"
};
let result = ("firstName" in person);Property values in an object can be other objects:
Example myObj = {
name:"John", age:30, myCars: {
car1:"Ford", car2:"BMW", car3:"Fiat"
}
}You can access nested objects using 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];Access properties with dot notation or bracket notation Add, change, and delete properties using assignment and delete Use the in operator to check if a property exists