DEV Community

Randy Rivera
Randy Rivera

Posted on

Else Statements

Introducing Else Statements

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? With an else statement, an alternate block of code can be executed.

  • Example:
function test(num) {
  var result = "";

if (num > 5) {
    result = "Bigger than 5";
  }

  if (num <= 5) {
    result = "5 or Smaller";
  }
  return result;
}
test(4);
Enter fullscreen mode Exit fullscreen mode
  • This is your basic if statement
function test(num) {
  var result = "";

 if (num > 5) {
    result = "Bigger than 5";
  } else {
    result = "5 or Smaller";
  }
  return result;
}
console.log(test(4)); // will display 5 or Smaller
Enter fullscreen mode Exit fullscreen mode
  • Here we combined the if statements into a single if/else statement.

  • If you have multiple conditions that need to be addressed, you can chain if statements together with else if statements.

function testElseIf(num) {
  if (num > 10) {
    return "Greater than 10";
  } else if (num < 5) {
    return "Smaller than 5";
  } else {
    return "Between 5 and 10";
  }

}
console.log(testElseIf(7)); // will display Between 5 and 10
Enter fullscreen mode Exit fullscreen mode
  • Logical Order in If Else Statements

Order is important in if, else if statements.

Take these two functions as an example.

  • Here's the first:
function logical(num) {
  if (num < 10) {
    return "Less than 10";
  } else if (num < 5) {
    return "Less than 5";
  } else {
    return "Greater than or equal to two";
  }
}
Enter fullscreen mode Exit fullscreen mode

And the second just switches the order of the statements:

function logic(num) {
  if (num < 5) {
    return "Less than 5";
  } else if (num < 10) {
    return "Less than 10";
  } else {
    return "Greater than or equal to two";
  }
}
Enter fullscreen mode Exit fullscreen mode

Now sure these two functions look identical but if we pass a number to both we get different outputs.

console.log(logical(4)); will display Less than 10
console.log(logic(4)); will display Less than 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)