Dot notation Property Accessor inside a function

This is my first post on a programming forum ever.

So i’m doing the “Basic Javascript” Module and i came across this challenge that teaches that you can use an object as substitute for a Switch Case chain. I got the challenge right after a little struggling, but couldn’t understand why the first attempts were wrong so i decided to practice the concept on VScode and wrote a function that tells the number order of any particular letter of the alphabet. And apparently what went wrong is that the dot notation (line 170) isn’t working to access the object property WHEN INSIDE A FUNCTION, but outside a function, it works. Why is that?

This isn’t related to being inside of function.

Dot notation cannot be used when accessing property of object using variable, only bracket notation can be used in such case.

Taking alphabet from your code as example:
Letter 'W' can be accessed directly by alphabet.W or alphabet['W'].
On the other hand code like

const letter = 'W';
console.log(alphabet.letter);

will not work, because letter after the alphabet. is not recognized here as letter defined in the line above. It’s recognized as a literally word letter.

In such situation, when using variable, it’s only possible to use bracket notation - alphabet[letter].

2 Likes

The issue is not dot notation inside of the function. The issue is that you cannot use dot notation with a variable that holds the property name. You must have the exact property name following the dot.


For future reference, its way easier for others to read copy-pasted code instead of a screenshot of code.

2 Likes

One more idea for seeing the difference - add to the alphabet, the letra property with a distinct value and notice in which cases that value is actually printed out and when it’s the value from the variable.

2 Likes