Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Object Properties

An Object is an Unordered Collection of Properties

Properties are a key component of JavaScript objects.

They can be modified, added, removed, and some may be read-only.

Accessing JavaScript Properties

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.”;

Adding New Properties

You can add new properties to an existing object by assigning them 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, `delete person[“age”];

Example

const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50,
  eyeColor: “blue”
};

delete person[“age”];

NOTE:

The delete keyword removes both the value of the property and the property itself.

After deletion, the property cannot be accessed until it is added back again.

 

Nested Objects

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];