Difference between ? and ?? in JavaScript/Typescript
source link: https://dev.to/saimwebhr/difference-between-and-in-javascripttypescript-f4d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Difference between ? and ?? in JavaScript/Typescript
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK