JavaScript is one of the most popular computer languages of all time, one of the reasons for this is the highly intuitive syntax of JavaScript. That's not even the best part, the best part is that a lot of new features are added to the language regularly.
Today we will see some of those new features help us with writing more intuitive code.
Nullish coalescing operator (??)
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
false || '@sun_anshuman'
false ?? '@sun_anshuman'
0 || '@sun_anshuman'
null || '@sun_anshuman'
null ?? '@sun_anshuman'
undefined ?? '@sun_anshuman'
The problem with || is that its a boolean operator so it coerces the left-hand operand to a boolean before evaluating, hence making both 0 and '' a false.
Use case by example
Let's assume you are building a game where the minimum score is 0 and you consider -1 an invalid score.
So before you update a user's score you would like to make sure it is set to a valid value or the defined invalid score.
let score = fetchScoreFromServer();
const finalScore = score || -1;
How to solve this, you ask? (I know you know it by now, haha)
let score = fetchScoreFromServer();
const finalScore = score ?? -1;
Logical nullish assignment (??=)
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).
let user = { name: "anshuman_bhardwaj" };
user.twitter_name ??= "@sun_anshuman";
console.log(user);
This is basically an assignment operation based on the ?? operator.
Use case by example
let finalScore = fetchScoreFromServer();
finalScore ??= -1;
Another good place to use ?? would be while referencing object properties and using default value. In which case we can use Logical nullish assignment ??= to give default values to undefined properties.
const user = { email: '[email protected]', company: '' }
user.name ??= email.split("@")[0]
user.company ??= 'Canoo'
in operator
The in operator returns true if the specified property is in the specified object or its prototype chain.
const user = { email: '[email protected]' }
'email' in user
'name' in user
You remember the time you were using undefined values because the referenced key was missing from Object.
It is worth noting that,
If you set a property to undefined but do not delete it, the in operator returns true for that property.
Use case by example
A good use case is to run sanity checks before running operations on an object's properties to avoid doing undefined checks and mistakes.
let user = { email: "[email protected]" };
if ("email" in user) {
if (!("name" in user)) {
user["name"] = user.email.split("@")[0];
} else {
console.log("Welcome user: " + user.name);
}
} else {
console.error("User does not have required property: email");
}
Using in on an array checks if the given index is an empty slot or not
const emptyList = new Array(5)
empties[2]
2 in empties
empties[2] = 'anshuman_bhardwaj'
2 in empties
Optional chaining (?.)
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is (null or undefined), the expression short-circuits with a return value of undefined.
let user = { name: 'anshuman' }
user.address.zipcode
user.addess?.zipcode
It is worth noting that,
- When used with function calls, it returns undefined if the given function does not exist.
- Optional chaining cannot be used on a non-declared root object but can be used with an undefined root object.
Use case by examples
const user = getUserFromDev()
console.log(user.email)
console.log(user?.email)
Conditional ternary operator (?)
The ternary operator checks whether the condition specified is true, if it's true then return the first expression else return the second expression.
x ? y : z, means if x is true return y else return z.
let user = { age: 22 }
user['status'] = user.age > 18 ? 'adult' : 'minor'
This operator is not specific to JavaScript, I first used it in C++.
Use case by example
let user = { email: "[email protected]" };
if ("email" in user) {
user["name"] = user.email.split("@")[0];
} else {
user["name"] = "Anonymous";
}
user["name"] = "email" in user ? user.email.split("@")[0] : "Anonymous";
Using ternary is a personal preference, it's good for doing inline expressions otherwise everything can be put as if-else
Bonus
Here are some examples with mix and match of the above features, let's see who all can answer correctly down in the comments.
const user = { email: '[email protected]', lastName: undefined }
user["firstName"] = "email" in user
? user.email.split("_")[0]
: "Anonymous";
user["familyName"] ??= 'Bhardwaj'
console.log('lastName' in user)
console.log('' ?? '@sun_anshuman')
Learn more
You can also watch this YouTube video where I explain these examples
You can also fork the CodeSandBox to try out examples.
I hope this post was helpful to you. Should you have any feedback or questions, please feel free to put them in the comments below. I would love to hear and work on them.
For more such content, please follow me
Until next time

Resources
MDN docs