Hi, I'm Nicholas Johnson!

software engineer / trainer / AI enthusiast

Conditionals

JavaScript comes with conditional statements, if, else if and else:

var a = 12;

if (a > 12) {
  alert("a was greater");
} else if (a < 12) {
  alert("a was smaller");
} else {
  alert("a was 12");
}

We use these a lot less than we might in other languages, preferring object literals or guard clauses in small functions. They are there though, if you want them.

== or ===?

In most languages == (double equals) means equal to. In JavaScript === (triple equals) means exactly equals to and == means equal to with type casting.

Type casting is fiddly stuff, and often behaves in unexpected ways. Good JavaScript programmers generally avoid ==.

You should use ===.

Exercise - Conditional logic

  1. Create a little program that tells you if it’s the morning, afternoon or night. You can get the hour of the day something like this:
// returns a number between 0 and 24
new Date().getHours();