MakeW3web

JavaScript Accessing and modifying properties

In JavaScript, there are two primary ways to access and modify the properties of an object: dot notation and bracket notation. Understanding how to use these notations is essential for working with objects and their properties.

  1. Dot notation:

Dot notation is a simple and intuitive way to access and modify an object's properties. To use dot notation, you write the object's name followed by a dot (`.`) and the property's name.

Syntax:

objectName.propertyName

Example:

const person = {
  firstName: "John",
  lastName: "Doe",
};

// Accessing properties using dot notation
console.log(person.firstName); // Output: John
console.log(person.lastName); // Output: Doe

// Modifying properties using dot notation
person.firstName = "Jane";
console.log(person.firstName); // Output: Jane
  1. Bracket notation:

Bracket notation is an alternative way to access and modify an object's properties. It is particularly useful when the property name is not known at the time of writing the code, or when the property name includes characters that are not valid in dot notation (e.g., spaces or special characters). To use bracket notation, you write the object's name followed by the property's name enclosed in square brackets (`[]`).

Syntax:

objectName['propertyName']

Example:

const person = {
  firstName: "John",
  lastName: "Doe",
};

// Accessing properties using bracket notation
console.log(person['firstName']); // Output: John
console.log(person['lastName']); // Output: Doe

// Modifying properties using bracket notation
person['firstName'] = "Jane";
console.log(person['firstName']); // Output: Jane

Bracket notation also allows you to access and modify properties using variables:

const propertyName = 'firstName';
console.log(person[propertyName]); // Output: John

Both dot notation and bracket notation are valid ways to access and modify an object's properties in JavaScript. Dot notation is usually preferred for its simplicity and readability when you know the property name and it is a valid JavaScript identifier. Bracket notation is more versatile, as it allows you to use property names that are not valid identifiers or when the property name is stored in a variable.

It is essential to understand and be comfortable with both notations to work effectively with objects in JavaScript.

Was this page helpful?