DEV Community

Discussion on: đŸŠžâ€â™‚ïž 11 JavaScript Tips and Tricks to Code Like A Superhero (Vol.2)

Collapse
 
crimsonmed profile image
Médéric Burlet

One that I love is this:

const someVar = null
const myValue = someVar || "default text"
Enter fullscreen mode Exit fullscreen mode

The or operator works the same as an elvis operator.

This is useful if you want to display a default value when you can't get data from an api or if some data is null for a key.

This can be chained with objects

const someVar = {foo: {bar: null}}
const myValue = someVar?.foo?.bar || "default text"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lampe profile image
Micha

With ES2021 we have ||= :)
Which makes the syntax even cooler

I made a video about new features here:
youtu.be/hxmFYToenxE

Collapse
 
crimsonmed profile image
Médéric Burlet

True but not fully supported yet

Thread Thread
 
lampe profile image
Micha

With the right babelJS version it is ;)

Thread Thread
 
crimsonmed profile image
Médéric Burlet

And then you're bringing big pieces of extra code for not much 😉 good way to slow websites.

Thread Thread
 
grzesiekgs profile image
Grzesiek Dunin-ƚlęczek

I would say that developer convenience is more than a lot. Also, few bytes of code for polyfill, definitely will not slow down the website.

Thread Thread
 
crimsonmed profile image
Médéric Burlet

I tend to think of client first. UX is more important than writing one word less. for a developer. between users having slow internet speeds, limited networks and not the greatest machines bringing one poly-fill here and there vs zero can make a huge difference. If you are making something just for you or limited public then why not but the difference in code between the statement I used vs using ||= is not that big that it would justify using a poly-fill on my end. If we were talking about a promise polyfill for example that would be a different matter.

But in the end everyone codes differently. So whatever suits your coding style then use it.

Collapse
 
lesleyvdp profile image
Lesley van der Pol • Edited

Love this one too, it's also useful to prevent errors when destructuring something that could be undefined:

const { foo, bar } = couldBeUndefined || {};
Enter fullscreen mode Exit fullscreen mode

This can prevent errors such as "Cannot read foo of undefined".