Conditional Statements
Conditional statements allow a program to choose different paths or actions based on whether a condition is true or false.
The
ifstatement executes code if a condition is true:
age = 20
if (age >= 18) { // The expression is true
console.log("Hello"); // This will be executed
}
if (age <= 18) { // The expression is false
console.log("Bye"); // This will not be executed
}The
if-elsestatement runs one block iftrue, another if false:
score = 70
if (score >= 60) {
console.log("You passed!"); // This will be executed if true
} else {
console.log("Try again."); // This will be executed if false, this execute
}We can concatenate various
if-elsestatements to check multiple conditions in order. We can concatenate as much as we want to check various statements
The
switchstatement is an alternative to multipleif-elsefor one variable with many possible values
Falsy and Truthy Values
An important thing to know is that the number 0, empty strings "" or '', the null, undefined, and NaN values are evaluated as false on conditions, and any other single values by themselves are evaluated as truelike a proof of existence.
We can check if an assigned variable will end up being considered
falseortrue. These are known as falsy and truthy evaluations
We can use falsy evaluations to assign default values to variables by using the
||operator. This will check the left-hand condition first, assigning it if it's truthy, or assigning a default value if it's falsy. This concept is known as short-circuit evaluation
Last updated