Decision Making in JavaScript
If...else statements, switch statements, ternary operators and logical operators.
When writing code, we often need to handle different decisions and execute specific actions based on certain conditions. For example, if the time is between 6am and 12noon, display 'Good Morning!'.
Conditional statements help to achieve this. In this post, we'll be exploring the different types of conditional statements and logical operators in JavaScript.
If...else Statements
The if
statement executes a block of code if a specified condition is metβthat is, the condition in the parentheses evaluates to true
.
const time = new Date().getHours();
// the above gets the time in a 24-Hour format
if ( time < 18 ) {
console.log('Good Day π');
}
The else
statement executes a block of code if a specified condition is not metβthat is, the condition evaluates to false
.
if ( time < 18 ) {
console.log('Good Day π');
} else {
console.log('Good Evening π');
}
The else if
statement is used to specify some new condition(s) if the first condition evaluates to false. There can be as many else if
statements as necessary. A default else
statement can be optionally added after the else if
statement(s) to run if none of the conditionals evaluate to true
.
if ( time < 12 ) {
console.log('Good Morning! π');
} else if ( time < 18 ) {
console.log('Good Day π');
} else {
console.log('Good Evening π');
}
The syntax of an if...else
statement is:
if ( conditionOne ) {
// block of code to be executed if conditionOne is true
} else if (conditionTwo ) {
// block of code to be executed if conditionOne is false and conditionTwo is true
} else {
// block of code to be executed if conditionOne is false and conditionTwo is false
}
Switch Statements
A switch
statement has an expression which is compared with values of each case
clause and if a match is found, the code associated with the case
is executed. The break
keyword indicates the end of a case
. If no case
matches but a default
clause is included, the code inside the default
will be executed.
switch (expression) {
case value1:
// code to be executed
break;
case value2:
// code to be executed
break;
default:
// default code to be executed
break;
}
switch
statements can be used as an alternative to if... else
statements especially if there are many conditions with a precise value to execute. It is considered a more concise way of writing conditionals.
const season = 'harmattan';
switch (season) {
case 'rainy':
console.log('Ready your umbrellas.');
break;
case 'harmattan':
console.log('Dusty π·');
break;
case 'dry':
console.log('Put on the air conditioner.');
break;
default:
console.log('Climate change is real.');
}
//Output: Dusty π·
Ternary Operators
The ternary or conditional operator tests a condition and returns one value if it is true
, and another if it is false
. The ternary operator is usually used as a shortcut for the if
statement.
Syntax:
condition ? expressionOne : expressionTwo;
If the condition before the ?
evaluates to true
, execute the code in expressionOne. If the condition evaluates to false
, execute the code in expressionTwo.
const score = 85;
score > 50 ? console.log('Good job π') : console.log('Try again βΉ');
// Output: Good job π
Logical Operators
Logical operators are used to compare values and the result of the comparison is either true
or false
. There are three types of logical operators.
They areβAND &&
, OR ||
, and NOT !
.
The AND &&
operator returns true
if the operands to the left and right evaluate to be true
.
2 > 1 && 1 < 2; // true
true && true; // true
1 > 2 && 2 > 1; // false
false && true; // false
The OR ||
operator will return true
if one of the operands is true
.
2 > 1 || 1 < 2; // true
true || true; // true
1 > 2 || 2 > 1; // true
false || true; // true
The NOT !
operator reverses the value of a Boolean.
2 > 1 && 1 < 2; // true
!(2 > 1 && 1 < 2); // false
!(true); // false
Logical operators can be used together with if...else
statements.
const age = 20;
const emptyAccountBalance = false;
if (age >= 15 && emptyAccountBalance ) {
console.log('Can buy alcohol.');
} else {
console.log('Cannot buy alcohol.');
}
// Output: Cannot buy alcohol.
const age = 20;
const emptyAccountBalance = false;
if (age >= 15 || emptyAccountBalance ) {
console.log('Can buy alcohol.');
} else {
console.log('Cannot buy alcohol.');
}
// Output: Can buy alcohol.
const age = 20;
const emptyAccountBalance = false;
if (age >= 15 && !emptyAccountBalance ) {
console.log('Can buy alcohol.');
} else {
console.log('Cannot buy alcohol.');
}
// Output: Can buy alcohol.
Conclusion
Decision-making in programming is as important as it is in our day-to-day lives. Conditional statements provide us with logic for executing blocks of code based on different conditions in order to obtain the desired output.
Thank you for reading and I hope you found this post helpful. π«