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
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"
}
}
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)
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)
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}`)
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)
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)
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)
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 ...
Top comments (13)
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 :)
Greatful for your feedback !
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]
)?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!
Thanks :)
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.
Thanks for your feedback !
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
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 !
Super intuitive and neat.
😇
I knew (and use) two of these but didn't know about default assignment and includes. That could come in handy! Thanks! :)
Thanks !