Photo by Juan Rumimpunu on Unsplash
Better if statements in JS
Using Ternary operator to write better if statements
Table of contents
Hi!
I wanted to cover one topic in this post I found very useful.
Usually writing code you use mostly if statements to check certain conditions. So creating cleaner if statements can be very good to keep your code clean.
Lets look at some examples.
If else
Standard approach would be to check some condition, then if it is true we do first order if it is false using else statement we execute second order.
let check = false;
function checkIfbad(){
if(check) {
console.log("check is true")
}
else{
console.log("check is false")
}
}
So how we can improve this? We can get rid of else statement.
If
In this approach we remove else statement and create two if statements. This method maybe isn't shorter but for the reader of the code it clearly states the conditions, so it is easier to read.
function checkIfbetter(){
if(check) console.log("check is true")
if(!check) console.log("check is false")
}
We can improve this even further. There is something like Ternary Operator that will allow us to make it better.
Ternary Operator
Ternary operator has three parts. First part is condition that we check,here we use ? operator. Second part is statement that we get when condition is true and last part is separated with : that is statement when our condition is false.
function checkIfbest(){
check ? console.log("check is true") : console.log("check is false")
}
What is also very useful using this operator is that we can chain the operators.
let isRaining = false
let isSunny = false
isRaining ? console.log("Its raining now")
: isSunny ? console.log("Its sunny now")
: console.log("Its snowing")
If you find any mistakes or you have ideas how to refactor my solutions to be simplier/ better please let me know :)