JavaScript: "if" and "else" statements

Table of Contents

if and else

[if]: The if...else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

if (something === something) { // To check equlity in data types use "==="
 do();
}   else {
 doThat();
}
if (something > something) { // <
 do();
}   else {
 doThat();
}

Combining comparators

  • &&: AND.
  • ||: OR.
  • !: NOT.
if (something > 70 && something <= 10) {
 do();
}
if (something != 2) {
 do();
}
}   else {
 doThat();
}

Challenge

FizzBuzz is a classic programming challenge and children’s game where counting numbers are replaced with “Fizz” for multiples of three, “Buzz” for multiples of five, and “FizzBuzz” for multiples of both 3 and 5 (15).

var output = [];
var count = 1;

function fizzBuzz() {
 // If (X%3=0) and (X%5=0) then FizzBuzz
 if (count % 3 === 0 && count % 5 === 0) {
  output.push("FizzBuzz");
 }
 // If [X%3=0] then Fizz
 else if (count % 3 === 0) {
  output.push("Fizz");
 }
 // If [X%5=0] then Buzz
 else if (count % 5 === 0) {
  output.push("Buzz");
 }
 // Else count
 else {
  output.push(count);
 }

 count++;
    console.log(output);
}