Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Quick tip about || vs ??
Benjamin🦸‍♂️Auzanneau™
Benjamin🦸‍♂️Auzanneau™

Posted on • Edited on

     

Quick tip about || vs ??

Thenullish coalescing operator will help us to define nullary values equality (null orundefined), unlike the || operator.

constbasketValue=0;constorBasketValue=basketValue||14;constnullishBasketValue=basketValue??14;
Enter fullscreen modeExit fullscreen mode

What happened here ?

Thenullish coalescing operator (the??) is alogical operator that returns itsright-hand side operand when itsleft-hand side operand isnull orundefined. Otherwise returns itsleft-hand side operand.

|| implicitly converts our number to nullish value and returns14.
?? checks the value ofbasketValue (different to nullary values) and returns0

So, in our example, theorBasketValue is equal to14 andnullishBasketValue is equal to0.

That's it, make good use of it !


I'm not a native English speaker so, thanks in advance if you want to improve my article with correct syntax/grammar/sentences.

I can accept all kind remarks :)

Cover byJC Dela Cuesta onUnsplash

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
brack0 profile image
Denis SOURON
  • Location
    Nantes
  • Joined
• Edited on• Edited

This is a really nice feature to pull apart nullish and falsy values. I'd love to have this kind of behavior in conditionnal evaluation. Sometimes zero (as number) or empty string are expected values and having to handle nullish versus falsy is not really elegant. Hope this will come soon.

CollapseExpand
 
necraidan profile image
Benjamin🦸‍♂️Auzanneau™
Senior Developer / Front-end enthusiast / JavaScript Hero / Podcaster 🏀🏒🍻🇨🇦🐿️🇫🇷🦸‍♂️🎙️🎧My podcast: https://anchor.fm/front-end-chronicles
  • Location
    Nantes
  • Education
    Master's degree in CS
  • Work
    Angular Jedi at Lucca
  • Joined
• Edited on• Edited

If you want to try it, it's available in TypeScript since the version 3.7 !
In other hand, you can also try it directly in some browsers.
dev-to-uploads.s3.amazonaws.com/i/...
Let's give it a try ! ❓❓

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Senior Developer / Front-end enthusiast / JavaScript Hero / Podcaster 🏀🏒🍻🇨🇦🐿️🇫🇷🦸‍♂️🎙️🎧My podcast: https://anchor.fm/front-end-chronicles
  • Location
    Nantes
  • Education
    Master's degree in CS
  • Work
    Angular Jedi at Lucca
  • Joined

More fromBenjamin🦸‍♂️Auzanneau™

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp