Hey folks, if you have opened this article that means you are curious about these 2 operators, how they operate, and what's the difference between these two. So without wasting any time, let's jump into details with a code example.
?
? is Optional Chaining Operator, also commonly named as null checker for objects. Its primary use is to check if an object exists or not.
Example
const user = {
id: 5,
name: "John"
};
console.log(user?.name); //John
console.log(user?.fullName); //undefined, program won't crash.
console.log(user.fullName);
//TypeError: Cannot read property ‘fullName’ of undefined
??
?? is Nullish Coalescing Operator. It is used to initialize an object/variable if it is undefined or null.
Example
const user = {
id: 5,
name: "",
firstName: null,
lastName: undefined
};
console.log(user.name??"Johnny Depp");// prints ""
console.log(user.firstName??"Johnny");// prints Johnny
console.log(user.lastName??"Depp");// prints Depp
Feel free to add suggestions in the comments.
Thanks. Happy Coding.
Top comments (20)
Hey!
I know what you meant, but the
user.fullName
don't crash. It just returnsundefined
.For it to crash you would need
user.fullName.somethingElse
.This is because the
user
object exists and it's not a problem to try access keys that don't exist.Also, this could be translation issues, but
??
works as||
, except, as you said, only withnull
andundefined
.As a tip: use 3 backticks (
`
) plus the language to print code:Great, thanks for the correction Bruno.
Another thing to keep in mind when you're checking for empty string (i.e ""). Nullish Coalescing Operator (??) will return false only if the variable is null. But Optional Chaining Operator (?) will return false if either the value is null or if it's an empty string.
Great, thanks
Just to clarify below code is Not Optional Chaining Operator but Ternary operator.
You learn something everyday! :)
Learning never stops :))
Thanks for the article!
Nice, i didn't know "??" Seems very helpful
Do give it a shot.
I love this article ❤️❤️
Glad to hear it.
Such an informational feed!
Thanks a lot buddy.
It returns true for 0 and false for Unknown and Null
Wow, thanks dude for the gain
Most welcome. Follow me for more articles. Happy Friday.
Clear information. Thanks!
I'm happy to help.