JavaScript Comparisons
JavaScript Comparison and Logical Operators
Section titled “JavaScript Comparison and Logical Operators”Comparison and logical operators are fundamental for making decisions and controlling the flow of execution in JavaScript programs. They evaluate to a Boolean value (true or false).
Comparison Operators
Section titled “Comparison Operators”Comparison operators are used in logical statements to determine equality or difference between variables or values. It is highly recommended to use strict comparison operators (=== and !==) to avoid unexpected behavior due to type coercion.
Given let x = 5;
Operator | Description | Example | Returns--- | --- | --- | ---`==` | Equal to (Loose Equality - performs type coercion) | `x == "5"` | `true` (Avoid if possible)`===` | Equal value and equal type (Strict Equality) | `x === "5"` | `false``===` | Equal value and equal type (Strict Equality) | `x === 5` | `true` (Recommended)`!=` | Not equal (Loose Inequality - performs type coercion) | `x != "5"` | `false` (Avoid if possible)`!==` | Not equal value or not equal type (Strict Inequality) | `x !== "5"` | `true``!==` | Not equal value or not equal type (Strict Inequality) | `x !== 5` | `false` (Recommended)`>` | Greater than | `x > 8` | `false``<` | Less than | `x < 8` | `true``>=` | Greater than or equal to | `x >= 5` | `true``<=` | Less than or equal to | `x <= 8` | `true`Understanding Type Coercion: Loose equality (==) attempts to convert operands to the same type before comparison, which can lead to counter-intuitive results (e.g., 0 == false is true, "" == false is true). Strict equality (===) does not perform type coercion; if types are different, it returns false.
Using Comparison Operators in Conditional Statements
Section titled “Using Comparison Operators in Conditional Statements”Comparison operators are commonly used in if, else if, while, and other control flow statements to make decisions.
const age = 20;let message;
if (age >= 18) { message = "Old enough to vote.";} else { message = "Too young to vote.";}console.log(message); // Output: Old enough to vote.You will learn more about conditional statements in a dedicated chapter.
Logical Operators
Section titled “Logical Operators”Logical operators are used to combine or invert Boolean values.
Given let x = 6; and let y = 3;
Operator | Description | Example | Result--- | --- | --- | ---`&&` | Logical AND: `true` if both operands are `true` | `(x < 10 && y > 1)` | `true` (true && true)`&&` | Logical AND | `(x < 10 && y < 1)` | `false` (true && false)`||` | Logical OR: `true` if at least one operand is `true` | `(x === 5 || y === 5)` | `false` (false || false)`||` | Logical OR | `(x === 6 || y === 5)` | `true` (true || false)`!` | Logical NOT: Inverts the Boolean value | `!(x === y)` | `true` (not false)`!` | Logical NOT | `!(x === 6)` | `false` (not true)Short-Circuiting: Logical AND (&&) and OR (||) operators exhibit short-circuiting behavior.
For expr1 && expr2, if expr1 is falsy, expr2 is not evaluated.
For expr1 || expr2, if expr1 is truthy, expr2 is not evaluated. This is often used for conditional execution or setting default values.
Example of short-circuiting with OR for default value:
const userName = null;const displayName = userName || "Guest"; // displayName becomes "Guest"The Nullish Coalescing Operator (??) (ES2020) is a related logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This is useful for providing defaults for variables that might be intentionally 0 or false.
const count = 0;const displayCount = count ?? 10; // displayCount is 0 (0 is not null or undefined)
const userSetting = null;const defaultSetting = userSetting ?? { theme: 'dark' }; // defaultSetting is { theme: 'dark' }Conditional (Ternary) Operator
Section titled “Conditional (Ternary) Operator”The conditional (ternary) operator is a concise way to write simple if-else statements.
Syntax:
Section titled “Syntax:”condition ? valueIfTrue : valueIfFalseExample:
Section titled “Example:”const userAge = 17;const canVote = (userAge >= 18) ? "Can vote" : "Cannot vote";console.log(canVote); // Output: Cannot voteIf userAge >= 18 is true, canVote is assigned “Can vote”; otherwise, it’s assigned “Cannot vote”.
Comparing Different Types
Section titled “Comparing Different Types”Comparing data of different types using loose equality (==) can lead to unexpected results due to type coercion. It’s generally safer to use strict equality (===) or explicitly convert types before comparison.
When comparing two strings, JavaScript performs lexicographical (alphabetical) comparison: "2" > "12" is true because ‘2’ comes after ‘1’ alphabetically.
To ensure a numeric comparison, convert strings to numbers:
let ageInput = "25"; // from a form input, for examplelet ageNumber = Number(ageInput);let isAdult;
if (isNaN(ageNumber)) { isAdult = "Invalid input";} else { isAdult = (ageNumber >= 18) ? "Adult" : "Minor";}console.log(isAdult); // Output: AdultNumber() converts an empty string "" to 0, and a non-numeric string (that cannot be converted) to NaN (Not a Number). Use isNaN() to check for NaN. |
|---|
JavaScript Bitwise Operators
Section titled “JavaScript Bitwise Operators”Bitwise operators treat their operands as sequences of 32 bits (zeros and ones) and perform operations on them bit by bit. These are less common in everyday web development but are used in some specific scenarios like graphics programming, data compression, or working with low-level protocols.
Operands are converted to 32-bit signed integers before the operation, and the result is converted back to a JavaScript number.
Operator | Description | Example (Simplified Binary)--- | --- | ---`&` | Bitwise AND | `5 & 1` (0101 & 0001) -> `1` (0001)`|` | Bitwise OR | `5 | 1` (0101 | 0001) -> `5` (0101)`^` | Bitwise XOR | `5 ^ 1` (0101 ^ 0001) -> `4` (0100)`~` | Bitwise NOT (inverts all bits) | `~5` (~0...0101) -> `-6` (1...1010 in two's complement)`<<` | Left Shift (shifts bits left, fills with 0s from right) | `5 << 1` (0101 << 1) -> `10` (1010)`>>` | Sign-propagating Right Shift (shifts bits right, fills with sign bit from left) | `5 >> 1` (0101 >> 1) -> `2` (0010)`>>>` | Zero-fill Right Shift (shifts bits right, fills with 0s from left) | `5 >>> 1` (0101 >>> 1) -> `2` (0010)Note: JavaScript uses 32-bit signed two’s complement representation for bitwise operations. This means ~5 results in -6, not 10 as a simple 4-bit unsigned example might suggest. Understanding two’s complement is key for ~, >>. |
|---|