Intro to the conditional methods
if
statement
Description Executes a block of code if a specified condition is truthy. Foundation of decision-making in logic.
javascript
/* Keep in mind that this example has fixed values, however,
you can replace any value with a value from a cookie, variable, form, input, etc. */
const userAge = 20;
let hasAccess = false;
if (userAge >= 18) {
hasAccess = true;
}
return hasAccess;
else
clause
Description Provides an alternative code block to execute if the if
condition is falsy.
javascript
/* Keep in mind that this example has fixed values, however,
you can replace any value with a value from a cookie, variable, form, input, etc. */
const userAge = 12;
if (userAge >= 18) {
return (hasAccess = true);
} else {
return (hasAccess = false);
}
Ternary operator (? :
)
Description Shorthand for simple if-else
. Returns one of two values based on a condition.
javascript
/* Keep in mind that this example has fixed values, however,
you can replace any value with a value from a cookie, variable, form, input, etc. */
const userAge = 12;
return userAge >= 18 ? 'Welcome' : "You can't join";
else if
ladder
Description Tests multiple conditions sequentially after an initial if
. Stops at the first truthy condition.
javascript
/* Keep in mind that this example has fixed values, however,
you can replace any value with a value from a cookie, variable, form, input, etc. */
const score = 85;
let grade = '';
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
return grade; // result: "B"
switch
statement
Description Compares a value against multiple cases. Use for readability with many fixed conditions.
javascript
/* Keep in mind that this example has fixed values, however,
you can replace any value with a value from a cookie, variable, form, input, etc. */
const day = 'Monday';
let activity = '';
switch (day) {
case 'Monday':
activity = 'Play guitar';
break;
case 'Friday':
activity = 'Play soccer';
break;
default:
activity = 'Play tennis';
}
return activity; // return: "Play guitar"