0
0
Javascriptprogramming~5 mins

Accessing object properties in Javascript

Choose your learning style9 modes available
Introduction

We use object properties to store and get information about things. Accessing these properties lets us read or change that information easily.

When you want to get the name or age of a person stored in an object.
When you need to update the price of a product in a shopping cart object.
When you want to check the status of a task in a to-do list object.
When you want to read settings like theme or language from a configuration object.
Syntax
Javascript
objectName.propertyName

// or

objectName["propertyName"]

You can use dot notation (objectName.propertyName) when you know the exact property name.

Use bracket notation (objectName["propertyName"]) when the property name is stored in a variable or has spaces/special characters.

Examples
Access the name property using dot notation.
Javascript
const person = { name: "Alice", age: 30 };
console.log(person.name);
Access the age property using bracket notation.
Javascript
const person = { name: "Alice", age: 30 };
console.log(person["age"]);
Use a variable key with bracket notation to access a property.
Javascript
const key = "name";
const person = { name: "Alice", age: 30 };
console.log(person[key]);
Sample Program

This program shows three ways to access properties of the car object. It prints the brand, model, and year.

Javascript
const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2022
};

console.log(car.brand);       // Using dot notation
console.log(car["model"]);  // Using bracket notation

const prop = "year";
console.log(car[prop]);       // Using variable with bracket notation
OutputSuccess
Important Notes

If you try to access a property that does not exist, JavaScript returns undefined.

Bracket notation is useful when property names have spaces or special characters, like object["full name"].

Summary

Use dot notation for simple, known property names.

Use bracket notation when property names are dynamic or have special characters.

Accessing properties lets you read or change information stored in objects.