Comparison
One of the most useful functions of any coding language is the ability to compare two or more values and return whether or not they are equal. Almost every conditional statement you write will make use of these comparison operators.
Comparison Operators
In JavaScript, data-type does not usually matter when comparing two values. Unless specifically stated otherwise, the values are converted to the same type at the time of comparison.
Name
Operator
Description
Example
Equal
==
returns true
if the values are equal, regardless of data-type
3 == 3 //true
; '3' == 3 //true
Not Equal
!=
returns true
if the values are not equal, regardless of data-type
3 != 4 //true
; '3' != 3 //false
Strict Equal
===
returns true
ONLY if the values are equal AND the same data-type
3 === 3 //true
; '3' === 3 //false
Strict Not Equal
!==
returns true
if the values are not equal OR not the same data-type
3 !== 4 //true
; '3' !== 3 //true
Greater than
>
returns true
if value A is larger than value B
4 > 3 //true
; 3 > 4 //false
Greater than or equal
>=
returns true
if value A is larger or the same as value B
4 >= 3 //true
; 4 >= 4 //true
; 3 >= 4 //false
Less than
<
returns true
if value A is smaller than value B
3 < 4 //true
; 4 < 3 //false
Less than or equal
<=
returns true
if value A is smaller or the same as value B
3 <= 4 //true
; 3 <= 3 //true
; 4 <= 3 //false
AND
&&
returns true
ONLY if value/condition A AND value/condition B are true
true && true //true
; true && false //false
OR
||
returns true
if EITHER value/condition A OR value/condition B are true
true
|| false //true
; false
|| false //false
File Location
We will be working in the following file:
Practice
In
comparison.js
, create a variable and assign it a value.Use the comparison operators to compare the variable to other values and print the results.
Use conditional statements and comparison operators to create a program with the following results:
If a person's age is over 25, they can rent a car. If a person's age is over 21, but less than 25, they can have a beer. If a person's age is over 18, but less than 21, they can vote. If a person's age is less than 18, make fun of them for being a child.
Last updated