top of page
  • Petri Silen

Best of future Javascript

Do Expressions

The do { .. } expression executes a block (with one or many statements in it), and the final statement completion value inside the block becomes the completion value of the do expression:

With do expressions you can get rid of annoying let variables and be able to use const instead as you should. I had a search "let" in one my side projects with big amount of code and most of found occurrences followed similar logic:

or using switch statement:

Using Do expressions I can rewrite them as follows and replace the lets with consts:

or using the switch statement inside do

Only bad thing is actually the syntax of do expressions. I would like to write them without the do part like this:

I have seen suggestions of using do expressions inside JSX in render function, but I don't use them. I recommend not to put much code inside JSX, but put the code in separate function(s), this makes the markup in JSX cleaner. I only allow myself to put maximum one or two non-nested ternary operators in JSX in render function.

Optional chaining and Nullish coalescing operator

We all have written hundreds or thousands of times expression similar to this:

It's quite a mouthful and I'd wish it could written shorter. And it can! Thanks to two new experimental JavaScript features: Optional chaining and Nullish coalescing operator a.k.a the Elvis operator. Using these two new experimental features I can write the above statement as follows:

?? operator is a great replacement for || operator. || operator checks for truthy values whereas ?? operator checks for nullish values: undefined and null. If the expression at the left-hand side of the ?? operator evaluates to undefined or null, its right-hand side is returned. Using || operator might cause subtle errors, when for example number values are evaluated. Number value zero evaluates to falsy value and might produce unexpected result when using || operator, but should work correctly when using ?? operator instead. Here is an example of potential error:

What happens when you supply a min value of zero? You get minValue of -100 instead of zero which is probably unexpected. Using ?? we can solve the problem:

Great News!

You can take these new experimental features using Babel plugins: Babel Optional chaining plugin and Babel Nullish coalescing operator plugin.

12 views0 comments
bottom of page