Sample Video Frame

Created by Zed A. Shaw Updated 2024-12-10 18:57:40
 

14: True and False Tests

A common operation in JavaScript is to test an equality of two variables (or values). You might want to know if a variable x is less than, equal to, or greater than another variable y. There are a large number of comparison operations that all fall into the category of "boolean logic", but in programming we'll call this a test. The end result of performing a test is true or false. You perform a test in JavaScript by using a "comparison operator" such as x == y or y != 1. Your computer's CPU even has a TEST instruction that does this.

Equal

In JavaScript, you can test the equality of two variables using == (double equals) or === (triple equals). You can think of == as "could be equal" and === as "definitely equal". You can play with node and try these examples out:

> 1 == '1'
true
> 1 === '1'
false
> '' == 0
true
> '' === 0
false

You can see that with == JavaScript will let you compare things that are seemingly very different like a numeric 1 and the string '1'. However, with === you'll be held to a stricter requirement that both sides of the === are exactly the same to be true. You should also look at the way I compare 0 to '' (an empty string). I explain this in the next part, but try to figure out why this happens in this example.

Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.