JavaScript branching

making decisions with if and else statements

// updated 2025-05-10 12:20

Branches make decisions with data based on cases:

"If" statements

Accounting for a situation:

1if (x == true) {
2    // if x is true, do something
3}
4
5// if it isn't, do nothing

"If/else" statements

Accounting for an either-or situation:

1if (x == true) {
2    // if x is true, do something
3} else {
4    // or else, do something else
5}

"If/elseif/else" statements

Accounting for a non-binary situation:

1if (x > 100) {
2  // if x is above 100, do something
3} else if (x > 50) {
4  // if x is between 50-100, do something else
5} else {
6  // otherwise, do something completely different
7}

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

1if (x > 100) {
2  // if x is above 100, do something
3} else if (x > 50) {
4  // if x is between 50-100, do something else
5} else if (x > 25) {
6  // if x is between 25-50, do something else
7} else if (x > 10) {
8  // if x is between 10-25, do something else
9} else {
10  // otherwise, do something completely different
11}

Switch statements

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

1switch (x) {
2  case (x > 100):
3    // do something
4    break;
5  case (x > 50):
6    // do something else
7    break;
8  case (x > 25):
9    // do something else
10    break;
11  case (x > 10):
12    // do something else
13    break;
14  default:
15    // do something completely different
16}

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 📒