Related Tags

javascript
communitycreator

# How to write an inline IF in JS

Chibueze Sam-Obisike

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:

1. Ternary operator
2. And logical operator
3. Without curly braces

### Ternary operator

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 useNotTruthy
return user ? userTruthy():useNotTruthy()
}

testFunc("A user")
testFunc("")

### And logical operator

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 useNotTruthy
return 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.

### Without curly braces

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);

### Explanation

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 $10$, we display the execution for each block.

Happy coding!

RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Chibueze Sam-Obisike
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time