How to use Equal and Not Equal Operators in Javascript

Description

The equal operator in Javascript is the double equal sign ==. The not-equal operator is !=.

They both do conversions to determine if two operands are equal as follows.

  • If an operand is false, converts it to 0 then compare.
  • If an operand is true, converts to 1 then compare.
  • If one operand is a string and the other is a number, convert the string into a number then compare.
  • If one operand is an object and the other is not, object's valueOf() method is called and then compare.
  • null and undefined are equal. null and undefined cannot be converted into any other values for equality checking.
  • If either operand is NaN, the equal operator returns false and the not-equal operator returns true.
  • If both operands are objects and point to the same object, then the equal operator returns true.

Example

The following example lists some special cases and their results:


console.log(6 == 6);                //true
console.log("6" == 6);                //true
console.log(null == undefined);       //true
console.log("NaN" == NaN);            //false
console.log(6 == NaN);                //false
console.log(NaN == NaN);              //false
console.log(NaN != NaN);              //true
console.log(false == 0);              //true
console.log(true == 1);               //true
console.log(true == 2);               //false
console.log(undefined == 0);          //false
console.log(null == 0);               //false
//from   w w  w  . jav a  2  s.c  o m

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions