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).

Build modern and responsive webpages

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

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

Ad