Comparison: ==, ===, !=, !==, <, >, <=, >=
1. Equality Operators
These operators check if two values are equal. This is where type coercion becomes very important.
a. Loose Equality (==)
- Compares two values for equality after performing type coercion if their types are different.
- Avoid using
==in most cases as it can lead to unexpected behavior due to implicit type conversions.
Examples:
b. Strict Equality (===)
- Compares two values for equality without performing any type coercion.
- It checks both the value AND the type. If the types are different, it immediately returns
false. - Always prefer
===over==for predictable and reliable comparisons.
Examples:
2. Inequality Operators
These operators check if two values are not equal.
a. Loose Inequality (!=)
- Returns
trueif the values are not equal after type coercion. It's the opposite of==. - Avoid using
!=for the same reasons you avoid==.
Examples:
b. Strict Inequality (!==)
- Returns
trueif the values are not equal without performing any type coercion. It checks both value and type. It's the opposite of===. - Always prefer
!==over!=.
Examples:
3. Relational Operators
These operators compare the order or magnitude of two values.
- Greater Than (
>): Returnstrueif the left operand is greater than the right operand. - Less Than (
<): Returnstrueif the left operand is less than the right operand. - Greater Than or Equal To (
>=): Returnstrueif the left operand is greater than or equal to the right operand. - Less Than or Equal To (
<=): Returnstrueif the left operand is less than or equal to the right operand.
Examples:
Important Note on String Comparisons:
When comparing strings with relational operators (<, >, <=, >=), JavaScript compares them lexicographically (alphabetically, based on their Unicode character values). This can lead to non-intuitive results if you're expecting numeric comparison (e.g., "20" > "100" is true). Always convert strings to numbers before comparing them numerically (e.g., using Number(), parseInt(), or parseFloat()).
Exercise: Comparison Challenges
In the editor below, write console.log() statements to output the result of each comparison. Pay close attention to strict vs. loose equality!
التالي · الدرس 12 من 61
Logical: &&, ||, !
قراءة 3 دقيقة
أنهيت 11 من 61 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

