It is quite common to use dot notation to access object’s props. How can you ever go wrong?
We have seen a bit of dot and bracket notations in all about Javascript objects and props post.
We have learnt to use dot notations to make our code more readable -
|
|
At the same time, you want to be careful with stuffing dots down the throat of every program. Note the following gotchas while using dot notation.
Reserved words and special characters
In bits and pieces across many programs, you may have also come to understand that using dot notations may not work as expected for reserved words and strings with special characters.
|
|
Non-existential Props
Dot notations may also throw errors when the said prop does not exist.
|
|
Primitives and methods
There are many other cases of primitives being accorded the treatment they don’t deserve when it comes to using dot notation to access a method.
Consider below examples where a string is treated as an object.
|
|
Numbers
Consider a number being treated as - well, a number.
|
|
While, this works -
|
|
In the above case, Javascript is trying to force a decimal on a number instead of seeing it as a method.
In Conclusion
Here are a few important points to keep in mind when using dot notations -
- Do not use dot notations on methods or props containing special characters or reserved words
- Always enclose numbers in brackets while using dot notation - lest it is confused with decimal point
- When in doubt about a prop, always use bracket notation. Looks ugly but gets things done