Hacking Javascript with operators
While coding in Javascript, I have found many helpful hacks that help me save tons of time, be more productive and write readable as well as elegant codes. Operators are one of them. So today I would like to share with you 5 of my favorite hacks using operators.
1) Short-circuit evaluation
Suppose you have the following code:
let canBuy = true;function buy() {
console.log('Buy');
}
Now instead of coding like this:
if (canBuy) {
buy(); //return "Buy"
}// you can code like this
canBuy && buy(); //return "Buy"
2) Converting to boolean using !! operator
In Javascript you can convert expressions which return one of the following listed values to false and any other values to true by using !! operator.
null;NaN; 0; empty string ("");undefined
This operator is really helpful when we want to check if some variable exists or if it has a valid value, to consider them as true value. To understand it in practice, take a look this simple example:
function setCanPrint(quantity) {
return !!quantity;
}console.log(setCanPrint(1)); // trueGet Hung HOANG’s stories in your inbox
Join Medium for free to get updates from this writer.
console.log(setCanPrint(undefined)); // false
3) + operator to convert a string to number
Simply return a corresponding number if it’s a valid string otherwise return NaN . Have a look on this example:
console.log(+'123'); // 123console.log(+'12a'); // NaN
This magic will work with Date too and, in this case, it will return the timestamp number:
console.log(+new Date()) // 14915636773074) Comma “,” operator to write readable and elegant code
The comma , operator can help you to write readable and elegant code if you know how to use it correctly.
hasCash ? (buy(), go()) : (saySorry(), exit());//Or in another example
for(var a = 1, b = 10; a*b; a++, b--) {
console.log(new Array(a*b).join('*'));
}
5) Default values using || operator
If the first parameter returns false the second one will be used as a default value. See this example:
function addProduct(_product) {
let product = {
unsold: _product.unsold || 0,
wrongLabels: _product.mistakes || 0
};
this.productsList.push(product);
}That’s it, I hope that these operators can help you write more readable and elegant code as well as be more productive while coding in Javascript. I will try to share with you more stuffs like this in the upcoming articles.








