Web Analytics

JavaScript Conditionals

Beginner ~15 min read

If, Else, and Else If

Conditional statements are used to perform different actions based on different conditions.

HTML
CSS
JS

The Switch Statement

Use the switch statement to select one of many code blocks to be executed. It's often cleaner than many else if statements.

HTML
CSS
JS
Don't forget break! If you omit the break statement, the next case will be executed even if the evaluation does not match the case. This is called "fall-through".

Ternary Operator

The ternary operator is a shorthand for if...else statements. It assigns a value to a variable based on a condition.

condition ? exprIfTrue : exprIfFalse
HTML
CSS
JS

Summary

  • Use if to specify a block of code to be executed, if a specified condition is true.
  • Use else to specify a block of code to be executed, if the same condition is false.
  • Use else if to specify a new condition to test, if the first condition is false.
  • Use switch to specify many alternative blocks of code to be executed.
  • Use the ternary operator (? :) for concise conditional assignments.

Quick Quiz

Which keyword stops the execution inside a switch block?

A
stop
B
break
C
return
D
exit