Control flow with if and switch

Using if/else and switch statements, we can control how code is execution.

if statement

The if statement is closely similar to any other programming language. Remember to NOT close any if expression statements with a semicolon.

if (score > 10) {
  alert("Congratulatiosn! You got 100%!");
} else if (score > 8) {
  alert("Wow! You rocked that quiz!");
} else if (score > 7) {
  alert ("You passed");
} else {
  alert ("Please review your notes and try again.");

The alert() is a browser object model function takes in a string and outputs it as a pop-up dialog message to the user.

Ternary if statement

You may have a ternary if statement for cleaner code.

Take a look at the code below. The left-most statement is the conditional. If it evaluates to true, the middle statement is executed. If false, the right-most statement is executed.

(name == "John") ? "Hello John" : "Hello unknown person";

switch statement

If you have several else-if statements, you may want to consider using a switch statement.

The switch statement evaluates an expression or a given variable, then delegates the task to whichever case it matches. If no matches are found, then the default is run.

switch (language) {
  case 'en':
    greeting = 'Hello world';
  case 'fr':
    greeting = 'Bonjour le monde';
  case 'es':
    greeting = 'Hola mundo';
    greeting = 'Greetings, earthlings';

Make sure to place a break; command after every case - otherwise JavaScript will continue to execute the next case (which is something you'll most often not want).

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Build modern and responsive webpages

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

$ Check price
29.9929.99Amazon 4.5 logo(63+ reviews)

More Front-end resources