Short & Sweet — JavaScript Conditionals

Meghan Elizabeth
2 min readMay 11, 2021
Photo by Chelsea Audibert on Unsplash

Conditional statements are programming instructions that are written to handle decisions- if a condition is true, perform that action, if the condition is false, perform the other action.

Comparison Operators

Comparison operators compare two values on either side of the operator.

Logical operators

Logical operators are used to determine logic between values

  • Logical AND — &&
  • Logical OR — ||
  • Logical NOT — !

If statement — Else if statement — Else statement

  • if — If a condition is true, then the code executes. If a condition is false, then the code doesn’t execute.
  • else if— After an if block, else if blocks can check additional conditions. If the if block is false, then check the additional else if's
  • else — We use this to specify for something else to happen when the condition(‘s) isn’t(/aren’t) met. If the if and else if conditions are false, then perform this code

Ex) In the code below, we set our oven temperature to 350 degrees to bake a cake! Will it burn 🤔? According to our code all oven temps greater than 325 will burn, all oven temps below 325 will be undercooked, and if our oven temp doesn’t fall into the previous categories (aka. if the oven temp = 325) then our cake will be perfect!

Switch statement

A switch statement can replace multiple if statements. It’s a way to compare a value against multiple case statements. The value of the switch statement is compared to the first case, then the next and the next. If the value and case statement are a match, switch starts to execute the code starting from the corresponding case until the nearest break. If no matching case is found, the program looks for default. Default is optional. If there is no default it will run until the end of the switch statement.

Ternary operator

Ternary operators are cleaner code for if-else statement’s. The ternary operator takes three operands.

syntax: condition ? expression1 : expression2

If the condition is true, the ternary operator returns expression1, if it’s false, it will return expression2

Ex) In the code below, we want to figure out if our cake will burn, or if it wont burn! So, if our oven temp is greater than 325 (condition), it will burn (expression1), if it’s not greater than 325, it won’t burn (expression2). We have our oven temp set to 350… uh oh

Summary

  • Use an if statement to perform an action if a condition is met
  • Use an else to perform an action if a condition isn’t met
  • Use an else if if you have several conditions
  • Use a switch statement if you have multiple if statements
  • Use a ternary operator if you have a condition with two expressions and to clean up code

--

--