IF statements are conditional statements where if a condition is true
, it is used to specify execution for a block of code.
I will be writing on how to use the following methods to write an inline if:
Ternary operators allow us to really quickly write shorter if statements.
Let’s assume if we have a variable called user
and we want to check if user
is true
, we then perform the userTruthy()
function. Otherwise, userNotTruthy()
should run.
function testFunc(arg){let user=arg;const userTruthy=()=>{console.log("User is Present")}const useNotTruthy=()=>{console.log("User is not present")}//If a user is present run userTruthy() else run useNotTruthyreturn user ? userTruthy():useNotTruthy()}testFunc("A user")testFunc("")
The and logical operator is another variant of an if system with a syntax of
conditon && execution block
If the conditon is true
, the execution block runs. Otherwise, nothing happens.
function testFunc(arg){let user=arg;const userTruthy=()=>{console.log("User is Present")}const useNotTruthy=()=>{console.log("User is not present")}//If a user is present run userTruthy() else run useNotTruthyreturn user && userTruthy()}testFunc("A user is here")testFunc("")
From the code above, we saw in the testFunc("A user is here")
the execution block ran, while in the testFunc("")
, which signifies false
, nothing happens.
const tryIF=(args)=>{if(args>10) console.log(`${args} is greater than 10`);else console.log(`${args} is not greater than 10`)}tryIF(29)tryIF(5);
In the above code, we basically put our if
condition and the execution statement in the same line.
We also do the same thing for the else
block.
In our test code above, we are checking for the value of args
. If it is greater or less than , we display the execution for each block.
Happy coding!