Javascript
JavaScript Fundamentals -- Objects in JavaScript

Accessing Key Values

PRO

After we create an object, we'll eventually need to access the data stored inside the keys on the object. We can do that in two ways, dot notation and bracket notation.

Dot notation looks like this:

const dog = {
    name: 'Duke'
}

console.log(dog.name); // Duke

We take the name of the object, dog in this case, add a period, and then the name of the key we want to access. Dot notation works for every type of key you can declare unless there's a dash or space in the key name. That's where bracket notation comes in handy.

const person = {
    'first-name': 'Preston',
    'last-name': 'Lamb'
}
console.log(person['first-name']); // Preston
const last = 'last-name';
console.log(person[last]); // Lamb

You can access the value of a key with bracket notation by putting the name of the object, immediately followed by opening and closing square brackets. A string value should be placed inside the square brackets (either directly or by way of a variable containing a string) and then the value is returned. If the keys have dashes or spaces in them, this is how you should access the keys.

You can read more about this in this blog post.