JavaScript if
Use the JavaScript if statement to execute a block of code when a condition is true.
if (hour < 18) {
greeting = "Good day";
}
Nested if
You can use an if statement inside another if statement:
let age = 16;
let country = "USA";
let text = "You can Not drive!";
if (country == "USA") {
if (age >= 16) {
text = "You can drive!";
}
}
The else Statement
Use the else statement to specify a block of code to be executed if a condition is false.
JavaScript Ternary Operator
The conditional operator is a shorthand for writing conditional if...else statements.
It is called a ternary operator because it takes three operands.
let text = (age < 18) ? "Minor" : "Adult";
JavaScript Switch Statement
switch is often used as a more readable alternative to many if...else if...else statements, especially when dealing with multiple possible values.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
}
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution inside the switch block.
The default Keyword
The default keyword specifies a block of code to run if there is no case match.
JavaScript Booleans
In JavaScript, a Boolean is a primitive data type that can only have one of two values:
true or false
The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.
Top comments (0)