You can access the properties of an object in JavaScript in 3 ways. Simple use Dot property or Square brackets to access objects in JavaScript.
- Dot property accessor:
object.property
- Square brackets property access:
object['property']
- Object destructuring:
const { property } = object
Access object in JavaScript
Simple example code access the property of an object using dot notation and bracket notation property. You can use the dot property accessor in a chain to access deeper properties: object.prop1.prop2
.
<!DOCTYPE html>
<html>
<body>
<script >
const Employee = {
f: 'John',
l: 'King'
};
// Dot
console.log(Employee.f);
console.log(Employee.l);
// Square brackets
console.log(Employee['f']);
console.log(Employee['l']);
console.log(Employee);
</script>
</body>
</html>
Output:
Object destructuring
<!DOCTYPE html>
<html>
<body>
<script >
const hero = {
name: 'Batman'
};
// Object destructuring:
const { name } = hero;
console.log(name); // 'Batman'
</script>
</body>
</html>
If property doesn’t exist in Object
If the accessed property doesn’t exist, all 3 methods will evaluate to undefined
:
const hero = { characterName: 'Batman' }; console.log(hero.name); // undefined console.log(hero['name']); // undefined const { name } = hero; console.log(name); // undefined
How to Dynamically Access Object Property Using Variable in JavaScript?
Answer: Use the Square Bracket ([ ]) Notation, Where the dot notation is easier to read and write, the square bracket notation offers much more flexibility since the value between the brackets can be any variable or expression.
var obj = {
name: "Peter Parker",
age: 16,
country: "United States"
}
// Property name stored in variable
var prop = 'name';
// Accessing property value
alert(obj[prop]); // Peter Parker
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