Almost a year back I came accross an interesting piece of code which used logical OR (||) in an assignment statement that looked something like this.
let testVariable = "Hello"; let evalResult = testVariable || "Bye"; console.log(evalResult);
Under the hood
Logical operators ( && and || ) are supposed to be used with booleans and when used with booleans it returns a boolean. But the interesting thing is, these operators are actually returning one of the operands based on their truth value.
Similarly logical AND (&&) checks for the truth value of the first operand and returns it, if its truth value is false else returns the second argument.
Using logical operators instead of tenary operator
We can take advantage of short circuit evaluation to actually replace some ternary operators with logical operators. Many times we endup in situations in which we have to return the value of a variable only when it is true or not null else return a default value or another variable. We can write a simple ternary operator for this situation which can be read as "If a is true return a else return the string" and it looks like this
let a; // a is undefined, will be evaluated to false let b = a ? a : "Something else, because a is false"; //ternary operation console.log(b); a = "I am a, and not false"; //a is a non empty string, will be evaluated to true b = a ? a : "Something else"; //ternary operator console.log(b);
The same code can be rewritten by using logical OR as below
let a; // a is undefined, will be evaluated to false let b = a || "Something else, because a is false"; //ternary operation console.log(b); a = "I am a, and not false"; //a is a non empty string, will be evaluated to true b = a || "Something else"; //ternary operator console.log(b);
Similary we can have a situation where we want return the variable only when it is false or evaluated to false else return something else. The ternary opertor for such a situation with variable name "a" can be read as "If a is false return a else return the string". Code examples follow
let a = false; // a is false let b = a ? "Something else" : a; //return a because a is false console.log(b); a = true; //a is true b = a ? "Something else" : a; //returns the string because a is true console.log(b);
The ternary operators can be rewritten using logical AND (&&) as below
let a = false; // a is false let b = a && "Something else"; //return a because a is false console.log(b); a = true; //a is true b = a && "Something else"; //returns the string because a is true console.log(b);
This simple trick makes your code much cleaner, concise and fancy.
Please feel free to share your feedback or any comments with me on my mail. If you like this article and think this can help any of your friends, dont hesitate to share this.