Skip to content

Conditionals

Conditionals (aka "if statements") allow you to make decisions in your code. With an if statement, you can evaluate whether a condition is true and, if so, run a specific section of code.

if (condition) {
  // do this stuff if the condition is true
}

You can require multiple conditions using && (and) or allow for either/or scenarios with || (or).

if (condition1 && condition2) {
  // do this stuff only if BOTH conditions are true
}

if (condition1 || condition2) {
  // do this stuff if EITHER condition1 OR condition2 is true
}

You can also create multiple branches using else or else if.

if (condition1) {
  // do this stuff if condition1 is true
} else if (condition2) {
  // do this stuff if condition2 is true
} else {
  // do this stuff if neither condition1 nor condition2 is true
}

Comparison Operators

You can specify conditions in if statements using the following comparison operators:

  • Strict equal ===
  • Not equal !=
  • Greater than >
  • Greater than or equal >=
  • Less than <
  • Less than or equal <=

For example, this tests whether the variable x is greater than 10:

const x = 11;

if (x > 10) {
  console.log("You win!");
}

This checks if the string variable exactly matches "Eric":

const myName = "Eric";

if (myName === "Eric") {
  console.log("Hey, that is my name, too!");
}

Try changing the comparison operators and operands in the examples below to see if the results match your expectations.

See the Pen Conditionals 1 (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.


See the Pen Conditionals 2 (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.