Wow. This article explains it so clearly. Thank you for this!
This is from the article you shared with me:
When working with bracket notation, property identifiers only have to be a String. They can include any characters, including spaces. Variables may also be used as long as the variable resolves to a String.
This means there are fewer limitations when working with bracket notation. We can now have spaces in our strings, and can even start strings with numbers.
Perhaps most importantly, we can now use variables to access properties in an object. It’s important the variable you are using references a String.
Take a look at this variable example. It might be a little confusing at first, so bear with me:
let obj = {
cat: 'meow',
dog: 'woof'
};
let dog = 'cat';
let sound = obj[dog];
console.log(sound);
// meow
The above example is similar to a previous example we’ve already seen. The main difference is we’re now using bracket notation to pass in a variable. Be careful, it may look like we are looking for the dog
property in our obj
, but that’s not entire correct. dog
is a variable with a value of 'cat'
. Since we’re using brackets, the string value is passed in and we search for the 'cat'
property — obj["cat"]
. Thus, meow
is logged to the console.
Below, we’ll try doing the same thing, but with dot notation:
let obj = {
cat: 'meow',
dog: 'woof'
};
let dog = 'cat';
let sound = obj.dog;
console.log(sound);
// woof
Right off the bat you should notice that we’re getting back woof
. This is very different from the other example and it’s because we can’t use variables with dot notation. Attempting to lookup obj.dog
will actually just look for the string value of 'dog'
within our object instead of using the variables value. Thus, obj.dog
returns woof
.