JavaScript branching

making decisions with if and else statements
// updated 2025-05-04 08:39

Branches make decisions with data based on cases:

"If" statements

Accounting for a situation:

if (x == true) {
    // if x is true, do something
}

// if it isn't, do nothing

"If/else" statements

Accounting for an either-or situation:

if (x == true) {
    // if x is true, do something
} else {
    // or else, do something else
}

"If/elseif/else" statements

Accounting for a non-binary situation:

if (x > 100) {
  // if x is above 100, do something
} else if (x > 50) {
  // if x is between 50-100, do something else
} else {
  // otherwise, do something completely different
}

We can place as many else if statements as we like:

if (x > 100) {
  // if x is above 100, do something
} else if (x > 50) {
  // if x is between 50-100, do something else
} else if (x > 25) {
  // if x is between 25-50, do something else
} else if (x > 10) {
  // if x is between 10-25, do something else
} else {
  // otherwise, do something completely different
}

Switch statements

A more aesthetically-pleasing "synonym" of the if/elseif/else structure:

switch (x) {
  case (x > 100):
    // do something
    break;
  case (x > 50):
    // do something else
    break;
  case (x > 25):
    // do something else
    break;
  case (x > 10):
    // do something else
    break;
  default:
    // do something completely different
}

Compare the keywords from the if/elseif/else and the switch!

⬅️ older (in textbook-javascript)
📒 JavaScript operators
newer (in textbook-javascript) ➡️
JavaScript looping 📒
⬅️ older (in code)
📒 JavaScript operators
newer (in code) ➡️
JavaScript looping 📒
⬅️ older (posts)
📒 JavaScript operators
newer (posts) ➡️
JavaScript looping 📒