Conditional flow in JavaScript
Let's get started
JavaScript Control Flow
if/else
if/else statements are how programs process yes/no questions programmatically. If the first condition evaluates to true, then the program will run the first block of code. Otherwise, it will run the else block.
Output:
else if
else if statements are used to add more conditions to an if/else statement.
Output:
True and False values
All JavaScript values have a truthy or falsy value. Declared variables are automatically given a truthy value unless the variable value contains any of the following:
false
0 and -0
โโ and โโ (empty strings)
null
undefined
NaN (not a number)
Note: To change a value from truthy to falsy and vice versa, use the following symbol: !
Comparison Operators
Less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=) symbols are used to compare values. Three equal signs (===) are used to check if the values are equal in value and type. An exclamation with two equal signs (!==) is used to check if two values do not equal each other. The comparisons evaluate to a boolean value (true or false).
Output:
Logical Operators
Logical operators allow us to determine if both or either of the compared values are truthy or falsy.
Use && to check if both values are true. Use || to check if either of the values is true.
Output:
switch
A collection of case statements that are compared to the switch condition and evaluated when the condition and case are true. A break is used between the cases to prevent additional execution. A default case gets evaluated when none of the cases are true. A switch statement accomplishes the same task an if/else if/else does in shorter lines of code.
Output
Ternary Operator
A ternary operator is a shorthand syntax for an if/else statement.
The first expression after the ? executes when the condition evaluates to true, and the second expression executes when the condition evaluates to false.
Output: