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

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?

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