logo
logo

Conditionals Cheatsheet

What is an if statement?

An if statement is a control structure in JavaScript that allows us to tell the code to run a block of code if a certain condition is true. This is very useful for checking conditionals, such as whether a variable has a certain value or whether something has started or not started.

Writing a basic if statement

Let's start by writing a basic if statement. The syntax for an if statement is as follows:

if (condition) {
  // code to execute if condition is true
}

In this example, the condition is what we want to check, and the code inside the curly brackets is what we want to execute if the condition is true. For example, if we want to console log something if a certain condition is true, we can write:

if (true) {
  console.log("Hi there");
}
This will log "Hi there" in the console unconditionally since the condition will always be
true
.

Using comparison operators in if statements

To make if statements more powerful, we can use comparison operators to compare values. The most common comparison operators are:

  • ==

    (double equals): checks for equality after doing type conversions

  • ===

    (triple equals): checks for equality without doing type conversions

  • !=

    (not equal): checks for inequality after doing type conversions

  • !==

    (strict not equal): checks for inequality without doing type conversions

  • >

    (greater than): checks if the left operand is greater than the right operand

  • <

    (less than): checks if the left operand is less than the right operand

  • >=

    (greater than or equal to): checks if the left operand is greater than or equal to the right operand

  • <=

    (less than or equal to): checks if the left operand is less than or equal to the right operand

Let's look at an example where we use the double equals operator:

const number = 5;
const stringNumber = "5";

if (number == stringNumber) {
  console.log("Equal");
} else {
  console.log("Not equal");
}

This will log "Equal" in the console, because the double equals operator does type conversions and checks if the values are equal.

Now let's use the triple equals operator:

const number = 5;
const stringNumber = "5";

if (number === stringNumber) {
  console.log("Equal");
} else {
  console.log("Not equal");
}

This will log "Not equal" in the console, because the triple equals operator does not do any type conversions and checks if the values are the same type and have the same value.

Nested Condtionals

Here's an example of a nested if statement:

if (bankAccountBalance >= costOfItem) {
  console.log('Checking tax');
  if (tax >= 0.5) {
    console.log('Tax amount too high');
  } else {
    console.log('Tax amount is fine');
  }
}

In this example, the outer if statement checks if the user has enough money to purchase the item. If the condition is true, the code inside the curly braces will be executed, and the inner if statement will check if the tax amount is too high. If the tax amount is greater than or equal to 0.5, the code inside the first set of curly braces will be executed. If the tax amount is less than 0.5, the code inside the else block will be executed.

It's important to note that nested if statements can become difficult to read and understand. It's generally a good idea to limit the number of nested if statements in your code.

Logical operators in JavaScript

AND operator (&&)

The AND operator is written as two ampersands (&&) and is used to combine two or more conditions. The code inside the curly braces will be executed only if all the conditions are true. Here's an example:

if (bankAccountBalance >= costOfItem && canSpendMoney) {
  console.log('You can purchase this item');
}

In this example, we are using the AND operator to check if the user has enough money to purchase the item and if they have indicated that they can spend money. If both conditions are true, the code inside the curly braces will be executed.

OR operator (||)

The OR operator is written as two vertical bars (||) and is used to combine two or more conditions. The code inside the curly braces will be executed if at least one of the conditions is true. Here's an example:

if (bankAccountBalance >= costOfItem || hasCreditCard) {
  console.log('You can purchase this item');
}

In this example, we are using the OR operator to check if the user has enough money to purchase the item or if they have a credit card. If either condition is true, the code inside the curly braces will be executed.

NOT operator (!)

The not operator is used to reverse the boolean value of an expression. If the expression is true, it will be false after using the not operator, and vice versa.

The or operator returns true if either of the expressions it is testing is true. If both expressions are false, it will return false.

Example of using the not operator:

let myName;
console.log(!myName); // output: true
let anotherName = "Billy Bob";
console.log(!anotherName); // output: false since a non-empty string is truthy.

What is a switch statement?

A switch statement is a type of control flow statement in JavaScript. It evaluates an expression and then matches the expression with different cases. When a match is found, the code in that case is executed. The syntax of a switch statement looks like this:

switch (expression) {
  case value1:
    // code to be executed when expression matches value1
    break;
  case value2:
    // code to be executed when expression matches value2
    break;
  ...
  default:
    // code to be executed when no case matches the expression
    break;
}

How to use a switch statement

Let's look at an example of using a switch statement. Suppose we have a variable
fruit
that contains the name of a fruit, and we want to log a message depending on the value of
fruit
. We can do this using an if-else statement like this:
const fruit = 'apple';

if (fruit === 'apple') {
  console.log('Awesome. I love apples.');
} else if (fruit === 'orange') {
  console.log('Oranges are cool.');
} else if (fruit === 'pear') {
  console.log('Pears are good too.');
} else {
  console.log('That sounds pretty okay.');
}

We can achieve the same result using a switch statement:

const fruit = 'apple';

switch (fruit) {
  case 'apple':
    console.log('Great, I love apples.');
    break;
  case 'orange':
    console.log('Good choice.');
    break;
  case 'banana':
    console.log('Okay.');
    break;
  default:
    console.log('I didn\'t understand that, but sure.');
    break;
}

Differences between switch and if-else statements

Switch statements can be a more elegant and readable way to handle multiple conditions compared to if-else statements. Switch statements are more suitable when there are multiple conditions to check against a single expression. The switch statement can provide faster execution when compared to if-else statements with multiple conditions.

Switch statements can also be used to stack multiple cases together. This takes advantage of the fact that code will execute until we break out of the code.

One important thing to remember is that the break statement is optional in switch statements, but it is recommended to use it. If the break statement is not used, all cases after the matching case will be executed.

How to use a switch statement in a function

Switch statements can also be used in functions. Let's say we have a function that takes in a number and sets the value of a variable based on the number. We can use a switch statement in the function to accomplish this:

function numChecker(num) {
  let value;

  switch (num) {
    case 0:
    case 1:
    case 2:
      value = 'low range';
      break;
    case 3:
    case 4:
    case 5:
      value = 'mid range';
      break;
    case 6:
    case 7:
    case 8:
      value = 'high range';
      break;
    default:
      console.log('Input number between 0 and 9');
      return;
  }

  console.log(`The value is ${value}.`);
}