I never write about great new JavaScript features on this blog. That is because there is really nothing you can not do without great new features, and I prefer writing compatible code (that runs in Internet Explorer).
However some code is backend-only, and if Node.js supports a feature I can use it.
So, here are two great new things in JavaScript that I will start using in Node.js.
Optional Chaining
It is very common in JavaScript with code like:
price = inventory.articles.apple.price;
If inventory, articles or apple is null or undefined this will throw an error. One common way to do this is:
price = inventory && inventory.articles && inventory.articles.apple && inventory.articles.apple.price;
That is obviously not optimal. I myself have implemented a little function, so I do:
price = safeget(inventory,'articles','apple','price');
The elegant 2020 solution is:
price = inventory?.articles?.apple?.price;
Who wouldn’t want to do that? Well, you need to be aware that it will “fail silently” if something is missing, so you should probably not use it when you dont expect anything to be null or undefined, and not without handling the “error” properly. If you replace . with ?. everywhere in your code, you will just detect your errors later when your code gives the wrong result rather than crashing.
Nullish Coalescing
It is very common to write code like:
connection.port = port || 80; connection.host = server || 'www.bing.com'; array = new Array(size || default_size);
The problem is that sometimes a “falsy value” (0, false, empty string) is a valid value, but it will be replaced by the default value. The port above can not be set to 0, and the host can not be set to ”;
I often do things like:
connection.port = 'number' === typeof port ? port : 80; connection.host = null == server ? 'www.bing.com' : server;
However, there is now a better way in JavaScript:
connection.port = port ?? 80; connection.host = server ?? 'www.bing.com'; array = new Array(size ?? default_size);
This will only fall back to the default value if port/server/size is null/undefined. Much of the time, this is what you want.
However, you still may need to do proper validation, so if you used to do:
connection.port = validatePort(port) ? port : 80;
you shall probably keep doing it.
Conclusion
If your target environment supports Optional chaining and Nullish coalescing, take advantage of it. Node.js 14 supports it.
0 Comments.