Select Page

Javascript Equality – Advanced Javascript Tutorial

Written by Asbar Ali


In this article, we are going to talk about javascript equality comparison and sameness in more detail with weird parts. So this will be useful for both beginner and advanced JavaScript developers.

(1) JavaScript Equality Comparison

Identity operator (===) behaves similarly to the abstract equality operator (==)  but type conversion is not done for an identical operator. Types of those 2 variables should be the same to be considered equal for identical operators.

(i) == (Abstract Equal Operator) – start to check equality after doing necessary type conversation and it checks only the values of 2 variables.

0 == false   //  Returns true and it is because false is equivalent of 0
2 == “2”      //  Returns true  and it is because String converted into number

(ii) === (Identity Operator) – This never does the type of conversation and if 2 values are not in the same type, it will return false. Simply, If 2 operands are the same type and have the same values, then only it produces true and otherwise, it returns false.

0 === false   //  Returns false and it is because both operands are of different type.
2 === “2”      // . Returns false.

These kinds of unexpected typecasting happen in javascript equality and we called Coercion. It can be categorized into 2 types.


(2) Implicit and Explicit Type Coercion

Cohesion: Process of conversion from one type to another.

Cohesion applies every data type in JavaScript and there are 2 types of cohesions. One (Implicity) is done by javascript and another one (Explicit) is done explicitly by us.

(i) Implicit Coercion – Type conversion is done by JavaScript.

//Output is 3 as both the strings are converted to number.
"15" - "12"

(ii) Explicitly Coercion – Type conversion is done using the inbuilt javascript function like String(), Number(), Boolean() etc.

// Output is 35, converted to number.
let number = Number("35"); 

 

 


(3) Should I use identity (===) or abstract (==) equality operator?

If you don’t want to learn or difficult to remember all the rules related to javascript equality, identify (===) operator is recommended to use in your code since it never does type conversion. So you will get the exact result as you expect and no need to worry about type conversion.

 

But in some cases, the double operator(==) is worth to use while working with data. Let’s take a simple example,

i) You want to concatenate 2 array by splitting with a comma –

["asbar", "ali"] + ','  + ["Sacheen", "Warnaka"]

Returns - "asbar", "ali", "Sacheen", "Warnaka"

ii) Check the equality of number get from form text input –

Even the user inputs the number, the value we get from the text input will be a string and it makes to do the additional step to convert it into a number but we can avoid it using the abstract equal operator (==).

const tpsValue = 5;
const textInputValue =  document.getElementById(myText).value; // returns “5” 

if (tpsValue == textInputValue) // Return true

(4)Which one has high performance (==) or (===)?

If compare 2 variables, the performance of both 2 operators is similar because they both use the same algorithm. But it changes when the types are different for both variables. Then identical operator (===) perform better than the abstract equal operator(==). It is because it does the extra step of type coercion.

If you want, you can check the performance test for both operators using the below link,

jsperf Test 1
jsperf Test 2

If you check those performance tests and you will realize that the performance shouldn’t play a role in deciding when to use one operator over another while you’re coding. If you don’t need to take advantage of the abstract equal operator (==), don’t use it because you might get some unexpected results.

Simply, use always identical operator (===) except when you need type cohesion.


(5) Implicit Coercion in identity (==) operator and if() condition

If the value in the if condition is not a boolean value, then implicitly it will be converted to the boolean type. If you use false, null, undefined, empty string, number zero, or number NaN  value for conditionals, it will return false. Everything else is treated as true.

if (undefined)    // false
if (0)            // false
if ('')           // false

Just memorize the following table and then you’ll able to tell the result of any values in if() condition. These all possible values that will be coerced to false and other values will give true.

Argument Type Result
Undefined false
Null false
String The result will be false if the argument is the empty String. It means the length of it is zero.
otherwise, the result is true.
Number The result will be false if the argument is –0, +0, or NaN valueOtherwise, the result will be true.
Object true.
Boolean The result equals the input argument and no conversion will happen here.

console.log(+0 === -0); //true
console.log(Object.is(+0, -0)); //false

console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); //true

console.log(Number.NaN === Number.NaN); // false
console.log(Object.is(Number.NaN, Number.NaN)); // true

console.log(NaN === Number.NaN); // false
console.log(Object.is(NaN, Number.NaN)); // true

(7) How !(Not) Operator works in JavaScript?

! operator is used to converting the value to its opposition. Since JavaScript does type cohesion, it will convert values to opposite boolean.

Note: Just memorize the following for ! operation and all other values in javascript will provide the result as false.

!0           // true
!NaN         // true
!null        // true
!undefined   // true

 

Check the following examples to get understand more.

(i) ! (Not) Operation for number – It’ll return false for all numbers except zero (0) because all numbers other than zero(0) gives the result true.

!1      // false
!-10    // false
!1.2    // false

(ii) ! (Not) Operation for array – It will always return false for array if we use ! operator.

var a = [];
!a; //false

(iv) The weird part in ! operator –  

If we do this, it is evaluated as true.

! + [] // true

 

The main reason is that the + operator only works on String and numbers. If use + operator with the array it converts it to an empty string. So check the detailed view as below,

! + []  
// Above will be converted internally into. 

! + String([])! + "" 	
//This will be evaluated as true because ! on empty string returns true

(8) How !! (Double Not) Operator works in JavaScript?

Use to converts value of any type to boolean. Double !! is not an operator in javascript and it’s just single ! operator twice. Single ! operator return inverted boolean but double operator !! returns non-inverted boolean and it is the true boolean representation.

!!1            // true
!!0            // false
!!undefined    // false
!!{}           // true
!![]           // true

 

Now let’s take a real-world example of fetching data from the endpoint. In the following example, let assume fetchedData gets data from the endpoint. But endpoint will return null at some point and then fetchedData also set to null. Now we want to check the data is received or not. So double !! operator would be better for it.

// This can be null at some point
const fetchedData = {name: 'Asbar', age: 25}; 

// If you want to know the fetchedData has values
console.log(!!fetchedData);

(9) How to check if 2 arrays are equal with the identical operator (===)

If you search google and you’ll get a lot of answers from StackOverflow to check 2 arrays.  But the people arguing each other over what the right way is. So isn’t it confusing? There is no right way and it depends on what you need.  So I picked one of those different approaches and let you explain the pros and cons of it.

 

Compare as String – The method is the easiest and fastest way to compare 2 arrays in javascript. First, it converts them into strings. (Using JSON.stringify()) and check using the comparison operator. (===)

var array1 = [1, 2, 3, 4, 5];
var array2 = [1, 2, 3, 4, 5];

if (JSON.stringify(array1) === JSON.stringify(array2)) {
	console.log('Both arrays are equal!');
}

When it doesn’t work? – The above solution would be okay if you compare two equal arrays with the same order. Check the following example and it doesn’t work with JSON.stringfy.

var arr2 = [1, 2, 3, 4, 5];
var arr3 = [5, 4, 3, 2, 1];

Above 2 arrays have the same length and exact same values but in a different order. Not worked. Now see another example where the above approach doesn’t work,

If an array contains objects and values but the order of object key might be different even 2 objects have the same keys and values. It would also fail using JSON.stringify method.

var arrObj1 = [1, 2, {a: 1, b: 2, c: 3}, 4, 5]; 
var arrObj2 = [1, 2, {c: 3, b: 2, a: 1}, 4, 5];

If you have any questions or queries, let us know in the comment section below.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Related Articles

Cool Gadgets on Amazon 2019 | Cool Amazon Products

Cool Gadgets on Amazon 2019 | Cool Amazon ProductsG, 0 Comments Today’s, topic about Cool Gadgets on Amazon 2019. Now, let's go and know about those gadgets in more deep. 01. The orange screwThis is one of the most clever and versatile tools you'll ever...

Is Interstellar Travel Impossible? | Interstellar Travel

Is Interstellar Travel Impossible? | Interstellar TravelG, 0 Comments Today's, topic about Interstellar Travel Impossible. Let's go into deep and understand the scientific facts related to this topic. Simply, Is interstellar travel doomed to remain in the...

Smart Retail Technology in IoT – Smart Retail Stores

Smart Retail Technology in IoT – Smart Retail StoresG, 0 Comments Today's topic is about "How IOT Gives Rise to Smart Retail Technology". Simply, I want you to picture your kitchen at home. If you're like most people you can trace many of your...

Stay Up to Date With The Latest News & Updates

Join Our Newsletter

Follow Us