Javascript
These operators form the foundation upon which logical decisions are made within a code.
JavaScript provides a set of comparison operators, including ==, ===, !=, and !==. Let’s take a closer look at how these operators work.
The == operator checks for equality, often performing type coercion.
5 == '5'; // true
The === operator enforces strict equality, comparing both value and type.
5 === '5'; // false
The != operator checks for inequality.
5 != '5'; // false
The !== operator enforces strict inequality.
5 !== '5'; // true
Logical operators (&&, ||, !) play a vital role in crafting conditional statements, allowing developers to control the flow of their code.
&&)The logical AND operator returns true if both operands are true.
if (x > 0 && y < 10) {
// Code block executed if x is greater than 0 and y is less than 10
}
||)The logical OR operator returns true if at least one operand is true.
if (day === 'Saturday' || day === 'Sunday') {
// Code block executed if the day is either Saturday or Sunday
}
!)The logical NOT operator negates the truth of its operand.
if (!loggedIn) {
// Code block executed if the user is not logged in
}
The ternary operator (? :) offers a concise way to write conditional statements.
let result = (age >= 18) ? 'Adult' : 'Minor';
This line of code checks if the age variable is greater than or equal to 18. If true, it assigns ‘Adult’ to the result variable; otherwise, it assigns 'Minor’.
JavaScript introduces logical operators to combine and manipulate boolean values.
Logical operators allow the combination of multiple conditions for more complex decision-making.
if (isMember || (purchaseTotal > 100 && loyaltyPoints > 50)) {
// Apply discount logic
}
Here, the discount is applied if the customer is a member or if their purchase total exceeds $100 and they have more than 50 loyalty points.
The nullish coalescing operator (??) is invaluable for handling null or undefined values.
let username = inputUsername ?? 'Guest';
In this example, if inputUsername is null or undefined, the variable username is assigned the default value 'Guest’.
The optional chaining operator (?.) simplifies the process of accessing nested properties within an object.
let city = user?.address?.city;
If any of the properties in the chain is null or undefined, the expression short-circuits, and city is assigned undefined.
| Operator | Description | Example |
|---|---|---|
| == | Equality | 5 == ‘5’ |
| === | Strict equality | 5 === ‘5’ |
| != | Inequality | 5 != ‘5’ |
| !== | Strict inequality | 5 !== ‘5’ |
| > | Greater than | 10 > 5 |
| < | Less than | 5 < 10 |
| >= | Greater than or equal to | 10 >= 10 |
| <= | Less than or equal to | 5 <= 10 |
If you want to know more about Operators, read this.