Conditional Statements By Chloe
If statements
If is a reserved keyword in Javascript, meaning it can not be used for anything else other than conditional statements.
var num1 = 10;
var num2 = 15;
if (num1 <= num2) {
console.log(`${num1} is less than $num2`);
}
=> 10 is less than 15.
In this example, the code would execute because 10 is less than 15. Else Statements
Often with code, even if the condition renders as false you want something to be executed.
var temp = 10;
if (temp >= 15){
console.log(It's hot outside, be sure to wear suncream!);
} else {
console.log(It's chilly out, remember a jacket!);
}
=> It's chilly out, remember a jacket!
This is because the temp variable was less than 15, therefore the condition was false so it moved onto the else statement.
Else...if Statements
Usually in Javascript more than one condition needs to be evaluated, and the user needs more than two different options. This is where an else...if statements is handy.
var money = 2.25;
if (money > 2.50) {
console.log('You can buy a chocolate bar and a drink');
} else if (money > 2) {
console.log('You can buy a chocolate bar');
} else {
console.log('You do not have enough money to buy anything');
}
=> 'You can buy a chocolate bar'
It ran the else if block of code because the if statement was false so it moved onto the else if statement which was true, the code stopped there and executed the block of code.
Ternary Operator
The ternary operator is a shorthand syntax for the if else statement, the syntax for this is:
var sky = blue;
var niceDay = (sky===blue) ? "what a beautiful day!" : "Not so nice today, is it?";
console.log(niceDay);
=> what a beautiful day!
Switch Statements
The switch statement can be used interchangeably with the else if statement. It will evaluate blocks of code against cases and execute one or more blocks appropriately.
var age = 20;
switch(true){
case age>=21:
'You can drink';
break;
case age=20:
'One more year then you can drink';
break;
default:
'Sorry, no drinking for you'
}
As age =20, the code block would return 'One more year then you can drink'.
Nested Condition Statements
A nested condition is an if statement within an if statement. An example of this would be:
if (5 > 2) {
console.log("If statement here!");
if(1 > 3) {
console.log("Nested if statement!");
} else {
console.log("Nested else statement");
}
} else {
console.log("Regular else statement");
}
=>