JS Tutorial
JS Object Properties
JavaScript Object Properties
An Object is an Unordered Collection of Properties
Properties are the most significant aspect of JavaScript objects.
Properties can be modified, added, or removed, and some are read-only.
Accessing JavaScript Properties
To access an object’s property, use the following syntax:
// 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.";
let x = "firstname";
let y = "age";
person[x] + " is " + person[y] + " years old.";
Adding New Properties
To add additional attributes to an existing object, just assign it a value:
Example
person.nationality = "English";
Deleting Properties
The delete keyword removes a property from an object.
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age;
Alternatively, remove person[“age”].
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person["age"];
Note:
The delete keyword removes both the property’s value and its contents.
The property cannot be utilized once it has been deleted until it is restored.
Nested Objects
An object’s property values can include other objects:
Example
myObj = {
name:"John",
age:30,
myCars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
To access nested items, use either the dot notation or the bracket notation:
Example
myObj.myCars.car2;
myObj.myCars["car2"];
myObj["myCars"]["car2"];
let p1 = "myCars";
let p2 = "car2";
myObj[p1][p2];