The 3 best Javascript operators you should use
Javascript is currently one of the most widely used programming languages but there are tricks when coding in JS that you should start using right away and this is what I'm going to show you in this short article.
Here are my top 3 Javascript tricks that will make your developer life easier.
1# The Nulling coalescing operator "??"
The double ?? in javascript is an operator that checks null or undefined values and helps you to assign a fallback value accordingly, call a function, or any other actions.
const codingSamples = null ?? 'Best coding media ๐'
// Best coding media ๐
const bankAccount = 0 ?? 42
// 0
2# The Logical Or operator "||"
The Logical Or operator is commonly used to check in a set of operands if one of them is true.
But the double || in javascript is an operator that also checks for null, undefined, 0, NaN, and empty string values.
const cash = 0 || 42000
// 42000
const name = '' || 'Simon'
// Simon
const isSet = (cash || name)
// true
3# The Optional chaining operator "?."
The last one is my favorite because it is the one I use the most.
The ?. operator in Javascript validates that each reference in a chain is valid (not null or undefined). This helps to prevent Cannot read property of undefined
.
const user = {
name: 'Coding Samples',
machine: {
name: 'Macbook',
version: 'Pro'
},
// linux: {
// version: 'Ubuntu'
// }
}
console.log(user.linux.version)
// Cannot read property of undefined
console.log(user.linux?.version)
// Undefined
console.log(user.machine?.name)
// Macbook
Conclusion
Here is how to code in Javascript more wisely and efficiently every day. Make sure to use Javascript operators in the best and smart way possible to make your code more readable and maintainable for others.