Comparison and Ternary Operators
Explore how JavaScript uses comparison operators to evaluate values, the difference between equality checks, and how the ternary operator simplifies conditional expressions. Understand truthy and falsy values, type coercion rules, and avoid common pitfalls to write better JavaScript conditions.
We'll cover the following...
Let’s see some booleans values. Booleans are either true or false.
Comparison operators
We can compare two numbers with >, >=, ==, ===, <=, <. We will discuss the difference between == and === soon. For the rest of the operators, the result of the comparison is a boolean.
The ! operator
The ! operator negates its operand. True becomes false, and false becomes true.
A truthy value is a value
vfor which!!vistrue. Examples of truthy values are: non-zero integers, strings containing at least one character.
A falsy value is a valuewfor which!!wisfalse. Examples of falsy values are: empty string,0,null,undefined.
We can convert a value to a boolean by negating it twice: !!:
- assuming
vis truthy,!vbecomesfalse.!!vbecomes!false, which becomestrue. - assuming
wis falsy,!wbecomestrue, and!!wbecomesfalse.
Equal to
For values a and b, a == b is true if and only if both a and b can be converted to the same value via type casting rules. This includes:
null == undefinedis true- If an operand is a string and the other operand is a number, the string is converted to a number.
- If an operand is a number and the other operand is a boolean, the boolean is converted to a number as follows:
truebecomes1, andfalsebecomes0.
Don’t worry about the exact definition; you will get used to it.
Equal value and equal type
For values a and b, a === b is true if and only if a == b and both a and b have the same types.
Not equal to
The negation of == is !=. Read it as is not equal to.
The negation of === is !==.
Ternary operator
Let me introduce the ternary operator to drive home a strong point about truthiness.
The value of a ? b : c is:
bifais truthycifais falsy
It is important to note the difference between 2 == true and !!2.
I have seen the nastiest bug in my life in a code, where a condition was in a format num == true. As I never felt like learning boring definitions, my lack of knowledge shot me in the foot because I assumed the opposite conversion in 2 == true. I can save you some headaches by highlighting this common misconception. In 2 == true, true is converted to 1, and not the other way around.
What is the functionality of ! operator?
Always returns false
Always returns true
Negates the operand