One Operator ? : Three Concepts
In this blog let's explore the JavaScript operator (?) which can be confusing sometimes. While writing this Pika was with me too, so excuse our talks.
Hello there, my dear friend! Are you tired of writing long, repetitive, and confusing code just to handle null values in JavaScript? writing endless if-else statements for the edge cases? Does your codespace is full of error handlers?
Fear not! In this blog, our company will (: what company, there is no company, you work for your own dude : oh yah sorry) Scratch that my friend, I will make sure from this moment, you will be writing super effective code without smashing your head (: everyone is not like you, they write better code : hmm ok)
So, buckle up and get ready to experience three superheroes of the coding world = Batman, Superman, Wonder woman (: man get out of DC, you are writing a Javascript blog : Oh F, sorry). Pardon my friend, they are = Ternary Operator, Optional Chaining, and Nullish Coalescing
Ternary Operator :
The ternary operator is a shorthand version of an if-else statement. It allows us to write a simple one-line code for conditional statements. The syntax for a ternary operator is
(condition) ? expressionIfTrue : expressionIfFalse
Here is a function that checks two numbers and returns which one is a greater
const compare = (a, b) => (a > b) ? "a is greater" : "b is greater";
But what if, there is a scenario where we just have to return true
or false.
You be like simple, do it like this
const compare = (a, b) => (a > b) ? true : false;
// ummm. actually no. we can just remove operator and its required statements and it will still return true or false based on the condition
const compare = (a, b) => (a > b);
// we should shorten the code, where there is scope, but yes without messing with the readability of the code
Nullish Coalescing
Nullish coalescing is another operator that allows us to handle null
or undefined
values in a more concise way. The nullish coalescing operator (??
) returns the value on its left-hand side if it is not null or undefined
, otherwise it returns the value on its right-hand side. The syntax is
const name = username ?? "Guest";
// if the user name will ever be NULL or UNDEFINED, then name variable will be assigned the value of GUEST.
But when is this useful? Whenever we are letting users or an API create an object, then it may be possible that the object ends up having undefined and null in some property. In those scenarios, it will be helpful.
Earlier this work is done by using OR
operator ||
, but one problem with that is if the value is 0
or a blank string ''
then also the default value is get shown. But with ??
, only Null and Undefined can trigger the default value.
Optional Chaining
So if we have to deal with Null
or Undefined
we get Nullish Coalescing, but what if we want to avoid an error? Null or Undefind
is still fine as it can be shown on a rendered page. But an error stops the code processing right away. So for that, we got Optional Chaining. Whenever and specifically the function where we are expecting an error, just after that we include a ?
and then if the error actually comes, then the function will return just an undefined
rather than throwing an error.
const person = {
name : "example",
age : 23
}
console.log(person.salary?.()) // output : undefined
// Here as we can see there is no method (function inside an object) called SALARY.
// so if we expected that error, we include a (?) after it. and it outputs undefined.
But why it is important? because if we get an error, then we can’t do anything at the user end, the code stops and app crashes and the user gets confused. Instead, if we know that this part is coming from some API or somewhere else and for that, it might throw an error, then we take Optional Chaining (?) include it in the code and gets an undefined
. and guess what, it is much easier (also better) to set a fallback for the undefined than an error.
Here all of them come together
(: Finally Justice League <3 : Dude not again, seriously : Oh sorry)
const obj = {}
const testFunc = obj => obj.test ? true : obj.salary?.() ?? "test failed"
console.log(testFunc(obj))
// Here all the three concepts are used : Ternary Operator, Optional Chaining and Nullish Coalescing in this same order
And that's it, my friends. I am sure from now on, any one of us won't be confused by this little sign of a question mark. See you in the next blog. Pika said Love Love to you all.