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?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ 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