# if-else statement

if else statement selectively run different part of codes based on if conditional statement is true or false

// if else example
const var1 = 10;
if(var1 < 9) {
console.log("Number is less than 9");
} else {
console.log("Number is greater than 9");
}


Output:

Number is greater than 9

As you can see in above code the condition checks if var1 is less than 9.

We can have different conditional operator like equal to , not equal to, equal to and of same data type, equal to value but not of same type, we will see example of these in this article

## Equal to

// if else example
const var1 = 10;
if(var1 == 10) {
console.log("Number is equal to 10");
} else {
console.log("Number is not equal to 10");
}


Output:

Number is equal to 10

## Not Equal to

// if else example
const var1 = 7;
if(var1 != 10) {
console.log("Number is not equal to 10");
} else {
console.log("Number is equal to 10");
}


Output:

Number is not equal to 10

## Equal in value and data type

// if else example
const var1 = 7;
if(var1 === '7') {
console.log("Number is equal to 7");
} else {
console.log("Number is not equal to 7");
}


Output:

Number is not equal to 7

As you can see in output

Equal in value but not in datatype

## Ternary operator

Ternary operator is mostly used as a one liner replacement to if-else statement

const age = 13;
console.log(age < 18 ? "Minor" : "Adult");


Output:

Minor

Compound conditional statements (and statement  - or statement)

## And condition

Example 1:


const age = 15;

// And operator
if (age > 12 && age < 20 ) {
console.log("Teenager");
} else {
consoloe.log("Not a Teenager");
}


Output:

Teenager

Example 2:

if we change afe from 15 to 50, output will be

Not a Teenager

So in example 2 when we changed age from 15 to 50 it is greater than 12 but not less than 20 hence since we have used and conditional operator so compound condition will be true only if both conditions are true. Now since second condition was not true in example 2 so compound condition was also not true.

Now if we use or conditional operator


const age = 50;

// OR operator
if (age > 12 || age < 20 ) {
console.log("Teenager");
} else {
console.log("Not a Teenager");
}


Output:

Teenager

When or operator is given then even if one condition is true that will be enough to make whole compound condition true.

if else conditions without using braces

Whenever your if else execution body only have one line you can skip braces around if else body

Example:

const var1 = 10;
if (var1 == 10)
console.log("TEN");
else
console.log("Not ten");


Output:

TEN