If you are still using the or(||) and(&&) operators in just if statement you need to read this.
Ternary operator
If you don't know what is ternary operator, is a simplified conditional operator like if / else.
it take three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
// With if else
if(condition){
expression1
}else{
expression2
}
// With ternary operator
connditon ? expression1 : expression2 ;
Is really useful and make your code short and clean if you care about your code quality, here few tips on how you can improve your code quality with the ternary operator :
let x;
5 > 0 ? (x = 'positive') : (x = 'negative'); //π
x = 5 > 0 ? 'positive' : 'negative'; //π
function myFunction(){
//π
if(5>0){
return true
}else{
return false
}
//π
return 5 > 0 ? true : false;
}
when to avoid it π«
- nested: of course, we can use two or more ternary operators inside each other but not recommended, you won't be able to read your own codeπ , so don't forget our goal to make the code clean and understandable.
- long expression: if you have a lot of lines of code to execute, either make the whole code in a function and call it or use the if/else statement.
AND operator(&&)
You may love using the ternary operator but what if you want to execute one expression if the condition is true "you can't do that!", here comes AND operator:
// with if statement
if(condition){
expression
}
// with and operator
condition && expression;
How it worksπ€, well the And operator always check the truthiness of the first statement, if falsy is skip whatever next came after, and if truety he pass to next.
don't forget to use it with a small expressions.
OR operator
On the contrary, the OR operator check the truthiness of the first statement if true he skipped the next one, so how we can use it?
For example, we expect an input value but we may get it or not, if we don't use backup our code will break.
function check(e){
const value = e.key ; //π
const value = e.key || "" ; //π
// here we say if e.key is falsy, value will be an empty string
console.log(value)
}
Nullish coalescing operator
The problem with the OR operator is that returns the right value if the left value is falsy 0, "", false, null, undefined
.
But if you want to return the right value when the left value is null or undefined better use nullish coalescing operator, you may not have heard about it before (I've also discovered it recently), he returns the right side if the left side is Null or undefined
// syntax
const value = e.key ?? "";
// here we say if e.key is equal to null or undefined
// value will be an empty string
Thank you for reading
These tips above really help me to improve my code quality, I'm sure if you start using these tips the right way, they gonna take your code to next level.
Top comments (0)