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';
    break;
  case 'fr':
    greeting = 'Bonjour le monde';
    break;
  case 'es':
    greeting = 'Hola mundo';
  default:
    greeting = 'Greetings, earthlings';
    break;
}

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?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ 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

Ad