JavaScript Conditionals

Post created on: 11/23/2019

Conditionals are a key part of every programming language but this post is specifically related to JavaScript.

Why use them? They can used to compare or check values e.g. a simple quiz if the answer is correct add 10 points to score if not no points added.

The simplest version is the use of if/else statements e.g.

if(condition is true){
    // do something
} else {
    // do something else
}

You can chain any number of else if statements e.g.

if (true) {
  // do something
} else if (condition) {
} else if (condition) {
} else if (condition) {
} else {
  // do something
}

While this will work if you have multiple conditions it can quite quickly get messy, but there is a shorthand you can use to make it less verbose. This is known as the tertary operator ? which follows format:

(condition) ? iftrue : iffalse;

It is important to remember that all values in JavaScript are considered truthy except those defined as falsy these are:

  • false
  • undefined
  • null
  • NaN (Not a Number)
  • 0
  • ' ' (empty string)
  • 0n