Conditional constructions allow you to perform certain actions depending on certain conditions:
if (condition) { actions }
Let’s consider an example:
var number = 10;//let's create a variable if (number > 5) {//if the value of our variable is greater than 5, then we execute the code in {} console.log("Yes"); } //otherwise, this code does nothing
This code can be shortened to:
var number = 10; if (number > 5) console.log("Yes");
Or like this:
var number = 10; if (number > 5) console.log("Yes");
The condition can be difficult:
var number = 5; var age = 18; if (number > 2 && age >= 12) { console.log("number is more than 5"); console.log("age is more than 12"); }
Check if the value exists
let number = 5; if (number) { console.log(`So it exists`); } let number2; if (number2) { console.log(`Nothing will happen`); }
Let’s check whether the variable is declared undefined and whether it is not null:
if (number !== undefined && number !== null) { console.log(`Yes`); }
Else
A set of instructions that is executed the if value is false:
if (Condition) { action if condition is true } else { action if condition is false }
For example:
let number = 5; if (number = 6) { console.log(`This will not work because if = false`); } else { console.log(`number is definitely not equal to 6`); }
You can shorten:
if (number = 6) console.log(`This will not work because if = false`); else console.log(`number is definitely not equal to 6');
Else if
With the else if construct, we can add an alternative condition to the if block:
const income = 50; if (income > 50) { console.log("Income over 50"); } else if (income === 50) { console.log("Income is 50"); } else { console.log("Income less than 50"); }
Switch case operator. Javascript example
July 24, 2022