Conditional Statements

Conditional statements allow a program to choose different paths or actions based on whether a condition is true or false.

  • The if statement executes code if a condition is true:

age = 20
if (age >= 18) {      // The expression is true
  console.log("Hello"); // This will be executed
}

if (age <= 18) {      // The expression is false
  console.log("Bye"); // This will not be executed
}

  • The if-else statement runs one block if true, another if false:

score = 70
if (score >= 60) {  
  console.log("You passed!"); // This will be executed if true
} else {
  console.log("Try again."); // This will be executed if false, this execute
}

  • We can concatenate various if-else statements to check multiple conditions in order. We can concatenate as much as we want to check various statements

if (temp > 30) {        // This is check first
  console.log("Hot");  // If true this is executed
} else if (temp > 20) { // If false, now this is checked, and so on
  console.log("Warm");
} else {
  console.log("Cool.");
}

  • The switch statement is an alternative to multiple if-else for one variable with many possible values

let day = "Sunday"
switch(day) {               // Compares this value with any case
  case "Monday":
    console.log("First day"); // First case
    break;
  case "Friday":
    console.log("Weekend"); // Other case
    break;
  default:                  // If there is no match, this will be taken
    console.log("A regular day"); // This will be executed
    break;
}

Falsy and Truthy Values

An important thing to know is that the number 0, empty strings "" or '', the null, undefined, and NaN values are evaluated as false on conditions, and any other single values by themselves are evaluated as truelike a proof of existence.

  • We can check if an assigned variable will end up being considered false or true. These are known as falsy and truthy evaluations

let falsy = 0;  // We declare the variable
if (falsy) {
  console.log("Exist");
} else {
  console.log("Not exist"); // This is executed, even know the variable exists
}

let truthy = 1;
if (truthy) {
  console.log("Exist"); // This is executed, as the value is not considered falsy
} else {
  console.log("Not exist"); 
}

  • We can use falsy evaluations to assign default values to variables by using the || operator. This will check the left-hand condition first, assigning it if it's truthy, or assigning a default value if it's falsy. This concept is known as short-circuit evaluation

let username = ''; // This is falsy
let defaultName = username || 'Guest';
console.log(defaultName); // This prints 'Guest'

let username2 = 'Joe'; // This is truthy
let defaultName2 = username2 || 'Guest';
console.log(defaultName2); // This prints 'Joe'

Last updated