Without even realizing it, most of your life is based on conditionals. If you haven't had a shower in a while, you shower. If you feel hungry, you eat. If you feel hot, you find ways to cool down. This type of statement is also essential for building programs, and all programming languages implement it in one way or another. So, how do you program logic in JavaScript?
You can do so by comparing values.
What Are Comparison Operators
First, you will have a look at the basic building blocks. Comparison operators compare the value on the left of the operator to the value on the right, and then return true or false.
The Most Common Comparison Operators
Have a look at the following operators:
==equal to!=NOT equal to<less than>greater than<=less-than or equal to>=greater-than or equal to
Try out these examples in the browser console:
5 == 5
"hello" != "Hello"
5.1 > 5
10 <= 9
"a" > "z"
Did you expect that result of the last one? Strings are compared based on their Unicode values, which are numerical representations of characters. JavaScript compares these character codes lexicographically, to determine if one is greater than the other.
The following makes reference to arrays [], which will come later in the course. Just know that an array that looks like that is an empty array.
Try it out yourself on the console!
Comparison Operator: Triple Equals
The difference between two equals signs and three equals signs often trips up new developers. The trip equals (===) compares the value and the type, so it is often preferred because it is much more specific. Specificity is generally good in programming, it makes things clearer and less prone to bugs. Have a look at these examples:
"10" === 10; // false
10 === 10; // true
"10" == 10; // true
This is the same with the not equals operators, != compares just value while !== compares both value and type.
Comparison Operator: Bang, Not or Logical Not
Bang operator, Not operator and Logical Not operator are three different names to reference an exclamation mark (!) which reverses the value of a boolean. You can also use the bang operator on its own too. This reverses the boolean in front of it:
!true; // false
!!true; // true
!false; // true
!(5 == "5"); // can you guess?
Summary: Comparison Operators in Javascript
- Conditional statements are essential to building programs
- Comparison operators are the building blocks of conditional statements
- They compare values and return
trueorfalse - The triple equals (
===) compares the value and the type - The Bang, Not or Logical Not operator reverses the value of a boolean
The Most Common Comparison Operators
==equal to!=NOT equal to<less than>greater than<=less-than or equal to>=greater-than or equal to