There are 2 ways to get properties from an object.
- use
.
- use
[]
eg.
const car = {
colour: 'red',
brand: 'tesla'
}
To get the colour
property, we can either:
console.log(car.colour); // red
or:
console.log(car["colour"]); // red
Why do we use the square bracket syntax?
Using the square bracket syntax allows us to get properties dynamically, i.e. we can put another variable inside the square bracket.
For example:
const colourText = "colour";
console.log(car[colourText]); // red