JavaScript Comparison Operators
Comparison operators are used to compare two values and return a Boolean value (true
or false
) indicating whether the comparison is true or false.
The following are the comparison operators in JavaScript:
==
: Equal to - returnstrue
if the two values are equal.===
: Strictly equal to - returnstrue
if the two values are equal and have the same data type.!=
: Not equal to - returnstrue
if the two values are not equal.!==
: Strictly not equal to - returnstrue
if the two values are not equal or have different data types.<
: Less than - returnstrue
if the first value is less than the second value.>
: Greater than - returnstrue
if the first value is greater than the second value.<=
: Less than or equal to - returnstrue
if the first value is less than or equal to the second value.>=
: Greater than or equal to - returnstrue
if the first value is greater than or equal to the second value.
Below are some examples of how to use comparison operators in JavaScript:
let a = 5;
let b = 10;
console.log(a == b); // false
console.log(a != b); // true
console.log(a < b); // true
console.log(a > b); // false
console.log(a <= b); // true
console.log(a >= b); // false
In the example above:
- We compare the values of
a
and b using different comparison operators. For example,a < b
is true because5
is less than10
.
When using the ==
operator, JavaScript performs type coercion to try to compare the two values. For example, 5
== '5'
is true
because JavaScript will convert the string '5'
to the number 5
before making the comparison. However, it's generally better to use the ===
operator when comparing values to avoid unexpected results due to type coercion.
Logical Operators
In JavaScript, logical operators are used to combine two or more Boolean expressions and return a Boolean value. The following are the three logical operators in JavaScript:
&&
: Logical AND - returnstrue
if both expressions are true.||
: Logical OR - returnstrue
if at least one expression is true.!
: Logical NOT - returns the opposite of the expression's Boolean value.
Below are some examples of how to use logical operators in JavaScript:
let a = 5;
let b = 10;
let c = 15;
console.log(a < b && b < c); // true
console.log(a < b || b > c); // true
console.log(!(a < b)); // false
In the example above:
- We use the logical operators
&&
,||
, and!
to combine multiple Boolean expressions. For example,a < b && b < c
is true because both expressions are true (5
is less than10
and10
is less than15
).
Logical operators have short-circuit evaluation, implying that the second expression is not evaluated if the first expression alone can determine the result.
This means that true || any_expression always returns true, regardless of the value of any_expression, and thus any_expression is not evaluated.