equality-comparison-in-javascript

Assessing entities in JavaScript is not an effortless task. Meanwhile, numbers, texts, and boolean values can be straightforwardly evaluated for equivalence. On the other hand, evaluating objects for equality is an entirely different matter. Whether you’re dealing with API responses, verifying form inputs, or managing state transitions in React, it is essential to understand the appropriate methods for comparing objects.

This article will delve into various techniques to compare JavaScript objects, addressing all approaches to carry out shallow and deep comparisons in JavaScript.

Contents:

Equality of Objects in JavaScript

Before diving deeper into the techniques for comparing objects for equality, it’s useful to comprehend the concept of object equality and its categories:

Referential Equality

Referential equality, often referred to as shallow comparison, ascertains whether two variables point to the same location in memory. If they do, they are deemed equal; if not, they are regarded as unequal.

Example:

JavaScript

Code Copied!

var isMobile = window.innerWidth “);

editor37289.setValue(decodedContent); // Set the default text editor37289.clearSelection();

editor37289.setOptions({ maxLines: Infinity });

function decodeHTML37289(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard37289() { const code = editor37289.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor37289 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor37289 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode37289() { var code = editor37289.getSession().getValue(); jQuery(“#runBtn37289 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “js”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1]; jQuery(“.output37289”).html(“

"+data+"");
									jQuery(".maineditor37289 .code-editor-output").show();
									jQuery("#runBtn37289 i.run-code").hide();
								}
							})
						}
						
function closeoutput37289() {	
	var code = editor37289.getSession().getValue();
	jQuery(".maineditor37289 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn37289").addEventListener("click", copyCodeToClipboard37289);
document.getElementById("runBtn37289").addEventListener("click", runCode37289);
document.getElementById("closeoutputBtn37289").addEventListener("click", closeoutput37289);


Output:

Referential Equality

Clarification: In this illustration, obj1 and obj2 are two objects possessing identical key-value pairs. The expression console.log(obj1 === obj2) yields false as both reference divergent memory addresses, regardless of their corresponding values. Furthermore, console.log(obj1 === obj3) shows true since obj3 merely points to obj1. The operator === assesses not only the components but also their references in JavaScript.

Deep Equality

Deep equality examines only whether the objects possess the same attributes and associated values or...not. It does not contrast with references or memory addresses.

Illustration:

Javascript
Code Duplicated!

"); jQuery(".maineditor6274 .code-editor-output").show(); jQuery("#runBtn6274 i.run-code").hide(); } }) }

function closeoutput6274() { var code = editor6274.getSession().getValue(); jQuery(".maineditor6274 .code-editor-output").hide(); }

// Link event listeners to the buttons document.getElementById("copyBtn6274").addEventListener("click", copyCodeToClipboard6274); document.getElementById("runBtn6274").addEventListener("click", runCode6274); document.getElementById("closeoutputBtn6274").addEventListener("click", closeoutput6274);

Result:

Deep Equality

Clarification: In this instance, obj1 and obj2 exhibit identical data, yet the === operator interprets them as distinct. Therefore, to achieve a deep equality analysis, alternative methods must be employed.

Techniques to Compare Objects in JavaScript

Below are several techniques for comparing objects in JavaScript. Let’s review each one individually:

Technique 1: Manual Comparison

This is the conventional approach to compare objects in JavaScript. Here, a recursive function verifies each property and value of both objects.

Illustration:

Javascript

Code Duplicated!

var isMobile = window.innerWidth ");

editor61712.setValue(decodedContent); // Establish the default text editor61712.clearSelection();

editor61712.setOptions({ maxLines: Infinity });

function decodeHTML61712(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard61712() { const code = editor61712.getValue(); // Retrieve code from the editor // Additional function logic omitted for brevity } ```javascript
// Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code successfully copied to clipboard!");

jQuery(".maineditor61712 .copymessage").fadeIn();
setTimeout(function() {
jQuery(".maineditor61712 .copymessage").fadeOut();
}, 2000);
}).catch(err => {
console.error("There was an issue copying code: ", err);
});
}

function executeCode61712() {

var code = editor61712.getSession().getValue();

jQuery("#runBtn61712 i.run-code").show();
jQuery(".output-tab").click();

jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",

data: {
language: "js",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];

jQuery(".output61712").html("

"+data+"");
									jQuery(".maineditor61712 .code-editor-output").fadeIn();
									jQuery("#runBtn61712 i.run-code").hide();
									
								}
							})
					

						}
						
						
	function closeOutput61712() {	
		var code = editor61712.getSession().getValue();
		jQuery(".maineditor61712 .code-editor-output").hide();
		}

    // Add event listeners to the buttons
    document.getElementById("copyBtn61712").addEventListener("click", copyCodeToClipboard61712);
    document.getElementById("runBtn61712").addEventListener("click", executeCode61712);
    document.getElementById("closeOutputBtn61712").addEventListener("click", closeOutput61712);
 
    



Output:

Manual Comparison

Explanation: The isDeepEqual() function employs a recursive methodology to thoroughly compare two objects in JavaScript. Additionally, isObject() serves as a utility function that ensures the function solely engages in recursion on genuine objects.

Method 2: Leveraging JSON.stringify()

This is the most straightforward approach to compare objects in JavaScript. The JSON.stringify() method transforms objects into JSON strings for comparison. The sole downside is that if objects possess properties in a different sequence, JSON.stringify() cannot accurately compare them.

Example:

Javascript
Code Successfully Copied!

Output:

Using JSON.stringify()

Explanation: The JSON.stringify() first transforms objects into strings, then performs a comparison. Additionally, as you might know, strings are a primitive data type. Consequently, true is yielded as output.

Method 3: Utilizing Lodash Library

Lodash is a widely-used external library offering functions for executing ``````html profound object evaluation.

Illustration:

Javascript
Code Duplicated!

");
jQuery(".maineditor19681 .code-editor-output").show();
jQuery("#runBtn19681 i.run-code").hide();
}
});
}

function closeoutput19681() {
var code = editor19681.getSession().getValue();
jQuery(".maineditor19681 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn19681").addEventListener("click", copyCodeToClipboard19681);
document.getElementById("runBtn19681").addEventListener("click", runCode19681);
document.getElementById("closeoutputBtn19681").addEventListener("click", closeoutput19681);

Result:

Utilizing Lodash Library

Clarification: The isEqual() function from the Lodash library is employed to execute a thorough comparison between the objects in JavaScript.

Method 4: Employing the deep-equal Library

Another practical library is deep-equal. It also offers a straightforward approach to deeply compare objects.

Illustration:

Javascript

Code Duplicated!

var isMobile = window.innerWidth ");

editor63882.setValue(decodedContent); // Initialize the text editor63882.clearSelection();

editor63882.setOptions({ maxLines: Infinity });

function decodeHTML63882(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard63882() { const code = editor63882.getValue(); // Obtain code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!"); jQuery(".maineditor63882 .copymessage").show(); setTimeout(function() { jQuery(".maineditor63882 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode63882() { var code = editor63882.getSession().getValue();

jQuery("#runBtn63882 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "js", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: ``````javascript function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output63882").html("

" + data + "");
	jQuery(".maineditor63882 .code-editor-output").show();
	jQuery("#runBtn63882 i.run-code").hide();
}
})
}

function closeoutput63882() { var code = editor63882.getSession().getValue(); jQuery(".maineditor63882 .code-editor-output").hide(); }

// Bind event handlers to the buttons document.getElementById("copyBtn63882").addEventListener("click", copyCodeToClipboard63882); document.getElementById("runBtn63882").addEventListener("click", runCode63882); document.getElementById("closeoutputBtn63882").addEventListener("click", closeoutput63882);

Output:

Utilizing the deep-equal Library

Clarification: The deepEqual(obj1, obj2) function is also employed to carry out a thorough comparison of objects in JavaScript. To utilize the deep-equal library, it is necessary to install it as a dependency.

Performance Evaluation

JavaScript offers numerous techniques for object comparison. Each technique exhibits various performance characteristics:

  • The JSON.stringify() method is quick and straightforward but fails when comparing objects that possess identical properties but in different sequences.
  • A recursive comparison is precise, yet it tends to be slower for deeply nested objects.
  • The Lodash and deep-equal libraries are viable alternatives for intricate comparisons, though they necessitate downloading these libraries as external dependencies.

Final Thoughts

Object comparison in JavaScript can be challenging; however, the appropriate method relies on your requirements. For uncomplicated comparisons, JSON.stringify() is suitable, while for complex comparisons, Lodash or deep-equal libraries are more effective. Grasping these methods enables you to execute object comparisons effectively.

How To Compare Two Objects For Equality in JavaScript – FAQs

Q1. How do you verify if two objects are equal in JavaScript?

To assess whether two objects are equal in JavaScript, you must evaluate if their properties and values correspond. You may utilize JSON.stringify(), or you can leverage libraries such as lodash or deep-equal.

Q2. Is it possible to use == for comparing objects?

No, utilizing == or === on objects solely verifies if they occupy the same memory address. const obj1 = { name: "Intellipaat" }; const obj2 = { name: "Intellipaat" }; console.log(obj1 == obj2); console.log(obj1 === obj2); In both scenarios, the output is false, irrespective of whether the objects are identical.

Q3. When should === be utilized in JavaScript?

Employ === (strict equality operator) when comparing primitive values such as numbers, strings, and booleans. This operator checks both the values and types.

Q4. What purpose does Lodash serve?

Lodash is a JavaScript utility library utilized for managing arrays, objects, and functions. It is also used to facilitate deep comparison via the .isEqual() method.

Q5. How can you compare two objects using Lodash?

Initially, you need to install lodash as a dependency. Following that, you can utilize the .isEqual() method for comparing objects. Syntax: console.log(lodash.isEqual(obj1, obj2));

The article Equality Comparison in JavaScript first appeared on Intellipaat Blog.

```


Leave a Reply

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

Share This