Tuesday, June 15, 2021

    JavaScript Equality Operator

    Must Read

    We started this site to inspire young minds to motivate and encourage them towards Programming Language. In this site you will get programming tutorials, tech, programming facts, programming fun and programming blogs.

    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

    Case1: Having 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 2: Compare 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 3: Compare 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 4: Compare 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 5: Compare 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.

    See more:

    Learn animation using CSS3, Javascript and HTML5

    Best JavaScript Resources to add Voice Control

    JavaScript Developers really need frameworks

    Previous articleHappy Programmer’s Day
    Next articleTry and Catch

    Latest Articles

    More Recipes Like This