In JavaScript, you can access an object inside another object using dot notation or bracket notation. Dot notation involves chaining the property names together with dots, while bracket notation involves passing the name of the property as a string inside square brackets.
You can also use variables to access properties using bracket notation.
Dot notation
Dot notation is the most common way to access nested objects. It uses a dot (.) to separate the names of the nested objects. For example, to access the name
property of the address
object inside the user
object, you would use the following code:
const name = user.address.name;
Bracket notation
Bracket notation is less common than dot notation, but it can be useful when you need to access a nested object by its index. For example, to access the second element of the addresses
array inside the user
object, you would use the following code:
const address = user.addresses[1];
Access object inside the object in JavaScript example
Simple example code.
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
console.log(person.name);
console.log(person['age']);
console.log(person.address['street']);
console.log(person['address'].city);
console.log(person['address']['state']);
Output:
Also note that when using bracket notation, you can use variables to access properties dynamically, like this:
const property = 'name';
console.log(person[property]); // Output: John
Both dot notation and bracket notation are valid ways to access an object inside another object in JavaScript. Here is a comparison of the two notations:
Dot notation | Bracket notation |
---|---|
Uses a dot (.) to access a property of an object | Uses square brackets [] to access a property of an object |
Property names must be valid identifiers, i.e. they can’t contain spaces or special characters | Property names can be any string, enclosed in quotes |
Properties can’t start with a number | Properties can start with a number |
Properties are case-sensitive | Properties are case-sensitive |
Easier to read and write for simple properties | Can be more flexible for dynamic properties or properties with special characters |
Can’t be used to access properties with special characters or reserved words, such as “class” or “if” | Can be used to access any property of an object |
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version