Tuesday, 19 September 2017

JAVASCRIPT EQUALITY OPERATOR


You’re marvelling why that part of code inside an if block is being executed while you expected it to be glance right! Well, let’s easy and see what’s incident under the hood to understand why quite that is happening.
You’re awestruck why that piece of code inside an if block is being performed while you expected it to be fly right! Well, let’s try and see what’s happening bottom the hood to understand why strictly that is happening.
Javascript supports two types of equality operators:
  • The Equality Operator(==) and
  • The Strict Equality Operator (===)
The equality operator deal with the “types” of the operands being compared and applies some rules on the operands with honour to type conversion.

web zone
web zone

Two values are strictly equal only if they have the same type and the same value. We will focus on the equality operator in this post since, well, there’s not much to highlight with respect to the strict equality operator J.
I hope you are aware of the primitive data types in JavaScript:
  • Boolean
  • Strings
  • Numbers

CASE1HAVING THE SAME TYPE OF BOTH OPERANDS 

This is the easiest case. If both the operands are of the same type, then compare their values. No type conversion required.

CASE 2COMPARE A STRING AND A NUMBER

  1. The string is converted to a number.
    1. Does the string represent a valid number: Compare the values.
    2. The string does not have a valid number(NaN): Return false.

CASE 3COMPARE A BOOLEAN TO A NUMBER

  1. Convert the Boolean to a number. True evaluates to 1, false evaluates to 0.
  2. Compare the values.

CASE 4COMPARE A BOOLEAN TO A STRING

  1. Convert the Boolean to a number. True evaluates to 1, false evaluates to 0.
  2. Convert the String to a number.
  3. Compare the values.

CASE 5COMPARE UNDEFINED TO NULL

Evaluates to true. Strange but true. Since both null and undefined represent “no value” (i.e. an object with no value and a variable with no value respectively.)

SOME RULES OF TYPE CONVERSION:

  • The string” ” converts to 0
  • Anything compared to NaN evaluates to False.
  • Anything (except null) compared to Undefined evaluates to False.

No comments:

Post a Comment