A skilled developer must always be updated about the latest changes in the world of programming. Despite the current situation and worldwide lockdown, we believe finding out more about programming can even be a good chance to fill the gap. The good news is there are new features in ES2020 you might want to check out. Our Front-end engineer, Armen shares his thoughts and experience with the latter, which will help you have a closer and more professional look at the latest updates of ES2020.
As a Front-end engineer, I like almost all the new features introduced in ES2020, and now I'd like to share with you some changes I've made based on one of the ES2020 features into my existing code.
Long chains of property accesses in JavaScript can be error-prone, as any of them might evaluate to null or undefined.
Here is my example:
// Bad practice
const usernameLength = store.user.username.length;
Above code can easily throw an error if one of the properties is not found, and in order to avoid such an error we should check for property existence on each step, and it will look like this:
// Hard to read.
let usernameLength; if (store && store.user && store.user.username) usernameLength = store.user.username.length;
Then we can decide to use ternary operator:
const usernameLength = (store ? (store.user ? (store.user.username ? store.user.username.length : undefined) : undefined) : undefined);
I think it is still hard to read.
I assume you've faced such problems in your experience, but fortunately there is a new feature in ES2020 which helps us to write much more readable codes and avoid errors, so here is what our code will look like using optional chaining operator.
// Still checks for errors and is much more readable.
const usernameLength = store?.user?.username?.length;
With the optional chaining operator, JavaScript initializes usernameLength to undefined instead of throwing an error.
Armen’s experience with the new updated ES2020 features shows that the latter can be very useful by giving new privileges to the developers to make their experience even more effective and fun.