Parsing JSON with ECMAScript 2020

or how to write less and simpler code using the new features of ECMAScript 2020

Image for post
Image for post

My task for today is to get data from nested structures like this

Image for post
Image for post

and a little bit below I have

Image for post
Image for post

So if the exercise is to get the first title from this JSON response you could go with if else constructs checking the presence of attributes.

It is like an if-then-else hell of coding.

Or much better with only one if and using short-circuit evaluation

But in the end this is

  1. no fun
  2. much to code
  3. boring
  4. fault-prone

So what can we do about it with the new added extensions to JavaScript?

We can use

  1. Nullish coalescing operator
  2. Optional chaining operator

My first attempt was to to it this way

But this attempt fails, if there is no title at all, because the statement before the || results to [] and is therefore truthy. So it also does not help to use ??

A better implementation would be this

And using ?? it always gives me an empty string if it is undefined, null, ….

This solution is less to write, hopefully better to understand and not so boring during coding, I think.

See you

Developer since the 80'th, working at Forschungszentrum Jülich (http://www.fz-juelich.de) …

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store