To access properties of an object in JavaScript, you can use dot notation or bracket notation.
Dot notation involves using a dot .
followed by the property name to access the value. For example:
1const person = { name: 'John' };
2console.log(person.name);
In this example, we have an object person
with a property name
. We can access the value of the name
property using dot notation.
Bracket notation involves using square brackets []
and the property name inside the brackets to access the value. For example:
1const person = { name: 'John' };
2console.log(person['name']);
In this case, we use bracket notation to access the value of the name
property.
Both dot notation and bracket notation can be used interchangeably. There might be cases where you need to use bracket notation, such as when the property name contains special characters or spaces.
It's important to note that if you try to access a property that doesn't exist in the object, you will get the value undefined
.
1const person = { name: 'John' };
2console.log(person.age); // Output: undefined
Try running the code example to see the output.
xxxxxxxxxx
// Accessing Object Properties
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
}
const myCar = new Car('Toyota', 'Camry', 2022);
console.log(myCar.make); // Output: Toyota
console.log(myCar['model']); // Output: Camry