Never use the Dot operator in JavaScript
The translator’s note:
The point of this article is that we try to use deconstruction to get properties of objects
Default values should be set during deconstruction in case the deconstructed properties do not exist
Const {a = ‘hello’} = object
See this link for more destructuring uses: Destructuring Assignments of variables
If you’re not deconstructing everything, you’re doing it wrong.
These may be bold statements, but let me explain……
First, the dot operator (.) is used in many places. It’s all perfect. Knowing where and why dot operators are used is the focus of this article. But there is much more to deconstruction and what many developers don’t know about deconstruction.
Second, let’s start at the beginning. ES2019 introduces two new operators to JavaScript:
- Optional chains:
? .
- Null merge value:
??
That means we can write user, right? .name?? ‘Noname’ and do not care if user exists, if either user or name does not exist, there will be a fallback.
These are all good, but not as well deconstructed
Why….
Let’s start at the beginning
Photo by Mikaela Stenström on Unsplash
Perhaps you are playing with some home automation scripts, and you have typed a helper function for some data structure, as shown below. You know that Celsius does not always exist, so you can set a default value that will be returned when Celsius does not exist.
If atticdata.celcius has no value, a default value is returned, in this case 15
const getTemperature = (atticData) = > atticData.celcius || 15;
Copy the code
There are two serious problems with this function:
- If the object you give the function is uninitialized at some point, or is
undefined
When? This function will run with an error - if
atticData.celcius
for0
, this function returns15
(Not behaving as we expected)
Using the two new operators mentioned at the beginning, you can fix this function:
const getTemperature = (atticData) = >atticData? .celcius ??15;
Copy the code
Both problems have been solved. This is great.
Should we use it everywhere? The operator?
No, for two reasons:
- It would only hinder the readability of any known static structure, such as the API
JSON.parse
,window.localStorage.getItem
Or another identifier that has already been imported into the library - In most other cases where we work with any data, deconstruction is probably the better choice.
Continue with our example function above – it will be written in deconstruction as follows:
const getTemperature = ({ celcius = 15 } = {}) = > celcius;
Copy the code
It’s a little bit cleaner, and it actually becomes more versatile because it doesn’t necessarily judge its operation. We avoid naming. Any potential object can be given this function, which will try to safely extract a degree Celsius.
Another way to think about it is that in our functions, we never need to refer to a data object, only to what’s inside it. So we dug it up as early as we could.
Deconstruction as early as possible
Remember the right tools
Whenever you use point (.) When fetching the properties of the fetch object, stop and think about whether you’ve deconstructed the value you’re after.
It usually leads to shorter code and higher control. Mainly because defaults can be set, but also because it is possible to do multi-level deconstruction, “deep deconstruction,” and then set safe defaults along the way.
As mentioned earlier – static apis are known to not need to be deconstructed. However, any data, even some configurations that you might consider static, is worth deconstructing with default values.
Use deconstruction
Let’s see what we can do with deconstruction:
The example above is a higher-order function/ thunk/curried function/factory (dear child has many names) that exploits the deconstruction feature in a different way. Let’s analyze:
- Setting the default value at the first/highest level in both function headers ensures that we don’t crash with func()() (empty arguments).
- When using values (MSG), rename the long key names for more readable logic.
- If you only need content in member values, use deep deconstruction. But again, remember to add a default value to keep the deconstruction safe from collapsing if the member value does not exist.
- You can also use rest operators to handle all content that is not explicitly deconstructed, which is very powerful.
- If we both need to use the entire structure and internal values, we deconstruct them in function scope (otherwise in the function header, as early as possible).
- The deconstruction and REST operators are also available for arrays.
- If a value is used multiple times in a range, we do not have to repeat a long expression for it
options.pos.x
. Instead, it’s just x. Cleaner, safer and more efficient, because JS doesn’t have to exploit value every time.
conclusion
Here’s what you should know from this article:
- Once you use the dot operator (
.
) – Stop and think about whether this is the data you’re manipulating. If so – use deconstruction instead. - Deconstruct it early.
- Remember to set defaults, especially during deep deconstruction.
The translator’s note: