JavaScript Pills: accessing object keys using external variables
[clique aqui para ler em português]
This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!
Consider an object called shirt
with a key named color
storing the string 'blue'
:
const shirt = { color: 'blue'}
If we had to access the value of color
, we could either use the bracket notation shirt['color']
or the dot notation shirt.color
. Both choices are equivalent, right? Hold that thought!
Let’s now create a variable and save the string 'color'
inside it:
const myVariable = 'color';
Now, we can also use this variable to access the color
value within the shirt
object. We will first try the bracket notation. Watch this:
shirt[myVariable];// 'blue'
This is possible because, when executing this code, the myVariable
variable is replaced with its content, which is the string 'color'
. In practice, we are doing shirt['color']
.
Ok, that makes sense! But just out of curiosity, let’s try this same type of access using the dot notation?
shirt.myVariable;// undefined
…Uh, what? Undefined? What happened here?
It gets easy to spot the difference between both scenarios if you know this basic concept about JavaScript objects: underneath the curtain, all keys in an object are strings, even when the quotation marks are omitted — which is our case.
When running shirt.myVariable
, we are requesting JavaScript to find a key inside shirt
which corresponds to the string 'myVariable'
, which doesn’t exist. In practice, that was exactly the same as doing shirt['myVariable']
.
However, if you go back to using the bracket notation with shirt[myVariable]
, JavaScript doesn’t coerce (convert) the bracket contents into a string and looks for the variable instead — which is the behavior we expect.
That’s all for today and see you next time ❤