There are 2 ways to get access to the object properties in JS:
- Dot notation:
user.name
- Square bracket notation:
user['name']
In both cases we’ll get access to the property name
of the object user
.
The most common way to access the object properties in JavaScript is the dot.
You write something like user.age
or user.name
to get access to the
properties age
and name
of the object user.
const user = {
age: 25,
name: 'Ben'
}
console.log(user.age); // 25
An alternative is to provide the name of the object property as a string and put it in the square brackets.
const user = {
age: 25,
name: 'Ben'
}
console.log(user['age']); // 25
The result is the same - we log the number 25 to the console.
However, with the square bracket notation you can use other variables to access the JavaScript object properties dynamically.