In JavaScript, comparison and logical operators are used to compare values and create logical expressions. Comparison operators are used to compare two values and return a boolean value (true
or false
). Logical operators are used to combine or invert boolean values.
Comparison Operators
Here are the comparison operators in JavaScript:
==
equal to!=
not equal to===
strict equal to!==
strict not equal to>
greater than>=
greater than or equal to<
less than<=
less than or equal to
The ==
operator compares two values for equality, while ignoring their data types. The ===
operator compares two values for strict equality, which means they must have the same value and data type. The !=
and !==
operators are used to test for inequality.
let x = 10;
let y = "10";
console.log(x == y); // true
console.log(x === y); // false
console.log(x != y); // false
console.log(x !== y); // true
Logical Operators
Here are the logical operators in JavaScript:
&&
logical AND||
logical OR!
logical NOT
The &&
operator returns true
if both operands are true
, otherwise it returns false
. The ||
operator returns true
if at least one operand is true
, otherwise it returns false
. The !
operator inverts the boolean value of its operand.
let x = 10;
let y = 5;
let z = 0;
console.log(x > y && y > z); // true
console.log(x < y || y < z); // false
console.log(!(x > y)); // false
Short-Circuit Evaluation
One interesting feature of logical operators in JavaScript is short-circuit evaluation. This means that the second operand of a logical AND (&&
) or logical OR (||
) expression is only evaluated if necessary.
let x = 10;
let y = null;
console.log(x && y); // null
console.log(x || y); // 10
In the first example, y
is null, which is a falsy value. Therefore, the logical AND expression returns y
without evaluating x
. In the second example, x
is a truthy value, so the logical OR expression returns x
without evaluating y
.
FAQs
- What are comparison operators in JavaScript? Comparison operators are used to compare two values and return a boolean value (
true
orfalse
). Examples of comparison operators in JavaScript include==
,!=
,===
, and!==
. - What are logical operators in JavaScript? Logical operators are used to combine or invert boolean values. Examples of logical operators in JavaScript include
&&
,||
, and!
. - What is short-circuit evaluation in JavaScript? Short-circuit evaluation is a feature of logical operators in JavaScript that evaluates the second operand of a logical AND (
&&
) or logical OR (||
) expression only if necessary. - What is the difference between
==
and===
in JavaScript? The==
operator compares two values for equality, while ignoring their data types. The===
operator compares two values for strict equality, which means they must have the same value and data type. - What is the boolean value of null in JavaScript? The boolean value of null in JavaScript is
false
.