DEV Community

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

Posted on • Edited on

2 2

Quick tip about || vs ??

The nullish coalescing operator will help us to define nullary values equality (null or undefined), unlike the || operator.

const basketValue = 0;
const orBasketValue = basketValue || 14;
const nullishBasketValue = basketValue ?? 14;
Enter fullscreen mode Exit fullscreen mode

What happened here ?

The nullish coalescing operator (the ??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined. Otherwise returns its left-hand side operand.

|| implicitly converts our number to nullish value and returns 14.
?? checks the value of basketValue (different to nullary values) and returns 0

So, in our example, the orBasketValue is equal to 14 and nullishBasketValue is equal to 0.

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 by JC Dela Cuesta on Unsplash

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
brack0 profile image
Denis SOURON • 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.

Collapse
 
necraidan profile image
Benjamin🦸‍♂️Auzanneau™ • 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 ! ❓❓

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay