DEV Community

Cover image for 6 Nullish coalescing operators every javascript programmer must know !
sudarshan
sudarshan

Posted on

6 Nullish coalescing operators every javascript programmer must know !

TL:DR :

Most of the time out javascript code becomes clumsier if we inserted the multiple null checks for the several entities. Those checks are kind of mandatory and if those checks were removed then this happens

TypeError: Cannot read property 'xyz' of undefined
Enter fullscreen mode Exit fullscreen mode

For preventing the programme from crashing and also making a code a bit neater, in this article I will explain some ways to handle this tricky situations


For the sake of examples, I will use following object to show you some example usage of the operators

let person = {
    name: "sud",
    age: 21,
    hobbie: {
        first: "Code",
        secodn: "Chess"
    }
}
Enter fullscreen mode Exit fullscreen mode

Ternary Operator



Ternary operator is most commonly used operator in the code. Most programmers use this as the replacement of inline if --- else. This operator mainly used in the conditional rendering of components in React

//ternary 
let result = person.name === "sud" ? "Howdy Sud " : "Howdy Stranger"
console.log(result)
Enter fullscreen mode Exit fullscreen mode

It is pretty straight forward. before ? is the condition. immediately after ? symbol is the block for true value of condition and other is for false result of condition


💥 Super Powered Ternary Operator 💥



Ternary operator really shines when it is nested with itself and can be replace if ...... else ladder completely is used properly. In the following snippet, I used the operator as the if else block and made the code more readable for anyone

//ternary as if else 
let isAdult = person.age > 18 ?
        " You are adult :)"
        : age < 15 && age > 10  ?
        "You are on the way " 
        : "No Kids here "
console.log(isAdult)
Enter fullscreen mode Exit fullscreen mode

It's pretty simple here, Append multiple conditions with consecutive block and then put last else block for default condition


Default Assignment with ??



Default assignment is one of my favorite once. This allows me to provide the placeholder value with minimal code by which we can trust the values and can implement type safety at logical level


let sudsAge = person.age ?? 22
console.log(`Sud's age is ${sudsAge}`)

Enter fullscreen mode Exit fullscreen mode

Here we are assigning the default value to sudsAge if the person.age is undefined. It is pretty helpful. Thanks to this operator for saving us lengthy checks ❤


Multi Condition Evaluation with .includes()



Many times we have to check many conditions for both true / false values. For doing these, I used to write multi-line nested code of if and else block or use the switch statement. But here is the trick

//check with multiple conditions
let isSporty = ['Chess', 'cricket'].includes(person.hobbie.first) ? "true" : "Nope"
console.log(isSporty)
Enter fullscreen mode Exit fullscreen mode

By replacing array values with real condition, we can check for all true values. If any values returns false then it will won't proceed .


Check Presence of Property In Object Using ?.



This is most useful operator in day to day life. Whether you are dealing with async API calls or dealing with blocking tasks, we easily assume the key will be present in the response of an API or output JSON object of any operation But, what if key is absent of undefined. Here is the trick

let sudsHobbyFirst = person?.hobbie?.third 
console.log(sudsHobbyFirst)
Enter fullscreen mode Exit fullscreen mode

By using this operator we can make sure the property is present or not and perform checks / operations according to result.


Chaining Default Assignment and Membership Operator



Previously mentioned operator can be super powered if chained with the default assignment. We will assign the default value to variable if the property is undefined or absent.

//?. with ?? 
let sudsHobby = person?.hobbie?.third ?? "Nothing"
console.log(sudsHobby)
Enter fullscreen mode Exit fullscreen mode

Here, we are assigning the placeholder value for sudsHobby
(🤣 you will use this a lot 🤣 )


Final Thoughts



This my small try to explain you all the usage of some operators which could possibly make your code neater and smaller rather than your previous code

🤗Please let me know your thoughts in comments

🙏hanks For Reading ...

Oldest comments (13)

Collapse
 
cariehl profile image
Cooper Riehl

Good article!

I appreciate how you built up to the (in my opinion) most useful forms of null-checking, the ?. and ?? operators. Coming from a .NET background, I use this pattern frequently, so it's good to know that I can apply the same pattern in JavaScript.

Thanks for sharing :)

Collapse
 
sudarshansb143 profile image
sudarshan

Greatful for your feedback !

Collapse
 
metalmikester profile image
Michel Renaud

I knew (and use) two of these but didn't know about default assignment and includes. That could come in handy! Thanks! :)

Collapse
 
sudarshansb143 profile image
sudarshan

Thanks !

Collapse
 
sebalr profile image
Sebastian Larrieu

Good post but I don't agree that multiple ternary operators is a good idea. There even is a lint rule to prevent that. In my opinions it makes code harder to follow that if-else

Collapse
 
sudarshansb143 profile image
sudarshan

Thanks for you feedback !

but, I think It is preferential to whether or not we should use this kind of stuff !

I will definitely look into that !

Collapse
 
gleaming_cube profile image
Darren Harding

Great post. My personal preference would be to use .some() instead of .includes() as it will return early as soon as it resolves true, where .includes() will go through every item in the array when it probably doesn't need to. I would also agree that nested ternary is very hard to read so I would probably avoid that if I had to nest multiple conditions and just fall back to good old fashioned if/else.

But this is really useful, thank you.

Collapse
 
sudarshansb143 profile image
sudarshan

Thanks for your feedback !

Collapse
 
bhargavshah profile image
Bhargav Shah

Great job compiling this list!
Just want to point out the word operator in the title is misleading. There is only one nullish coalescing operator that is ??. These are all great ways to handle nullishness, but they are not all "operators".
Cheers!

Collapse
 
sudarshansb143 profile image
sudarshan

Thanks :)

Collapse
 
kwadoskii profile image
Austin Ofor

Super intuitive and neat.

Collapse
 
sudarshansb143 profile image
sudarshan

😇

Collapse
 
jinsasa profile image
Christian Grauer

I like this post very much, especially the "?. with ??" thing, which I didn't know before. Is there any similar thing for use with the bracket-syntax (like for person[itsName][myHobby])?