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.
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];
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.";
To add additional attributes to an existing object, just assign it a value:
person.nationality = "English";
The delete keyword removes a property from an object.
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age;
Alternatively, remove person[“age”].
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person["age"];
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.
An object’s property values can include other objects:
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:
myObj.myCars.car2;
myObj.myCars["car2"];
myObj["myCars"]["car2"];
let p1 = "myCars";
let p2 = "car2";
myObj[p1][p2];
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.