Why is it that two objects do not equate in Javascript?

Although there are similar questions on SO, none of them have the answer I need.

In JavaScript, if you execute the following code, the result will be false:

https://i.sstatic.net/c5T8t.png

I understand it has to do with how JavaScript is defined in the spec, but why is it this way? It doesn't seem logical.

If ("string" === "string") evaluates to true, then why doesn't ({ } === { }) evaluate to true as well?

I read somewhere that the equality algorithm was designed to mimic that of C++ or C#, but it seems like creating a new engine that uses significantly less fuel and not utilizing it just for consistency with other vehicles.

What was the reasoning behind defining JavaScript in this manner? Was there a specific purpose behind this decision, or was it done simply to align with industry standards?

Answer №1

{} is a special syntax in JavaScript used to create objects. Essentially, you can replace

var obj = new Object();

with

var obj = {};

Therefore, whenever you use {}, you are creating a new object.

The line you referenced, {} == {}, actually creates two distinct objects with no properties. In essence, they are similar. If you were to have an equals(obj1, obj2) method that compares the properties of both obj1 and obj2, it would return true if both objects had the same values for all properties.

However, the == operator does not examine properties; it checks if both objects point to the same object/reference.

On the other hand,

var obj1 = {};
obj2 = obj1;
console.log(obj2 == obj1); // returns true

returns true because both obj1 and obj2 point to the same reference.

Lastly, when it comes to the comparison of strings like "abc" == "abc", the == operator evaluates the actual string contents and returns either true or false based on them.

Answer №2

While strings are unchangeable, making two strings with identical contents essentially indistinguishable.

Conversely, objects and arrays have the capability to be modified, allowing them to be distinct even if they currently share the same values. Altering one will not necessarily affect another.

To illustrate, if obj1 == obj2, modifying obj1.x = 1 will result in a change to obj2.x as well.

Answer №3

In the realm of JavaScript, a string may be an object but is still considered a primitive like integers or booleans. This means they are always compared by their actual value, as primitives are defined as simple atomic values. For example, "string" == "string", 1 = 1, and true == true all hold true.

On the other hand, objects are complex types made up of multiple primitives, making them more intricate to compare. It is not as straightforward as checking for equal values - {name:'a',address:'b',phone:'c'} != {name:'a',address:'b'} due to differing attributes. The comparison becomes even trickier with slight attribute variations such as {name:'x',address:'y'} == {name:'a',address'b'}, or different attribute orderings like {name:'x',address'y'} == {address:'y',name:'c'}. These complexities make it difficult to implement a standard method of comparing complex objects.

Given this complexity, it is often left to the programmer to define the rules for comparisons between complex objects based on the specific scenario at hand.

One useful method implemented in programming languages is comparing if two object references are equal, which allows for validations like obj == null, obj == this, or obja == objb to determine the identity of the objects being referenced. In essence, primitives are compared by value while complex types are typically compared by reference, following the usual conventions across most programming languages.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an error stating "angular not found" when attempting to dynamically load my Angular scripts

My Angular application is running smoothly. However, I found it tedious to include multiple script tags in my HTML documents every time. To simplify this process, I decided to create a small script that would automatically generate the necessary tags for m ...

Adding up and finding the contrast between odd and even numbers

After successfully segregating the odd and even numbers, I am faced with a challenge in determining how to add the odds together and the evens together before subtracting them to find the final result. For example: (1 + 3 + 5 + 7 + 9) - (2 + 4 + 6 + 8) = ...

What causes the closure variable to be reset after iterating over JSON data using $.each method?

Take a look at this scenario: var elements = []; $.getJSON(data_url, function(result) { $.each(result, function(key, value) { elements.push(parser.read(value.data)); // at this point, "elements" contains items }); }); dataLayer.addElements( ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

The Electron BrowserWindow event triggered when the window is closed

Is it possible to retrieve values when closing a BrowserWindow in electron? Ideally, I am looking for a method to access the variables from the close event: win.on('closed', function(variables can be accessed) { console.log(variables + ...

Parsley JS failing to validate

I attempted to validate my form using parsley.js, following the instructions from the official documentation. However, for unknown reasons, it is not functioning as expected. Below is the code snippet: <div class="container"> <div class= ...

`What's the best way to merge 3 IDs after pressing a button?`

I attempted this code <p>Watch Series Online</p> <input type="search" id="imdbseries" class="Search" name="" value="" placeholder="IMDB ID"> <input type="search" i ...

Introduction to Interactive HTML Pinball Game

As a beginner in the realm of computer science, I've recently embarked on creating a simple pinball game. My approach to maneuvering the flippers involves switching between images that depict the flipper in an upwards and downwards position by utilizi ...

Implementing sliders for interactive functionality with an HTML table

I need to implement sorting and sliding features on an HTML table using jQuery. Sorting has already been achieved by utilizing the DataTable.js jQuery library. The challenge now is to incorporate a slider into the table, with all subject columns being scro ...

Object-oriented programming (OOP) implementation with asynchronous JavaScript and XML (

... I'm currently facing a situation where I have an object: function Page(daoService) { this.daoService = daoService; this.gamesList = this.daoService.getGamesList(); } // Rendering thumbs for main page Page.prototype.renderThumbs = functio ...

Error encountered during discord oauth request

While setting up a Discord login, I encountered an error after being redirected from the OAuth page. The error message indicates a response code 400 (Bad Request) after pressing authorize. {"status":"ERROR","error":"Respo ...

Numerous rotation and resizing transitions failing to function properly

I am looking to implement a rotation and zoom in/out effect during the transition between different rotations of an image when a specific trigger occurs. The zoom should happen simultaneously with the rotation. Check out this example here button.addEventL ...

What steps should I take to include a React component in my HTML document?

Struggling with incorporating a React component into my HTML, CSS, and Js website. I tried following the guide at , but it's not working as expected. I'm at a loss on how to proceed. Here is the code snippet of the component: class Card extends R ...

The ReactJS Application Cache Client fails to display the most recent updates

One issue I'm currently facing is with my application in production. Some clients have reported that they are unable to see the new changes unless they clear their cache completely. Using Techs: React Any suggestions on what steps I should take to a ...

Scaling texture to fit on a plane in THREE.js

I am attempting to 'fit-to-scale' a mapped image texture on a single plane, aiming to simulate the behavior of object-fit:cover. The image map needs to scale proportionally in order to cover the entire plane completely. I have experimented with ...

Acquire information using Vue through HTTP requests based on Router parameters

I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the route ...

Removing a specific item from an array

state = { filters: ['all'] } this.state.filters.includes('humans') ? this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown) I have a condition set up so that when I click on a button, ...

Access the URL with personalized request headers

Our team manages a collection of primary web pages that cater to various organizations. These pages undergo changes in appearance (fonts, images, etc.) depending on the organization accessing them. This customization is done through a unique HTTP Request H ...

Listening for button clicks in a Bootstrap drop down menu using JavaScript

I'm struggling to figure out how to detect button clicks in a drop-down menu. I've tried using Array.from to assign an event listener to each button in the drop-down, but it doesn't seem to work efficiently. It feels inefficient to assign in ...

How to tally objects within an array of nested array objects based on a specific property using JavaScript

My dataset looks like this: var data = [ { items: [ { id: 123 }, { id: 234 }, { id: 123 } ] }, { items: [ { id: 123 }, { id: 234 } ] ...