In what ways can two identical-looking arrays actually be distinct from each other?

Explore this JavaScript snippet:

var st, ary, ary1, ary2;
ary  = [["a","b","c"], ["d","e","f"]]; // 2D array
ary1 = ary[1];
st   = "d,e,f"; ary2 = st.split(',');
st   = typeof(ary1) + " " + ary1.length + " " + ary1 + '\n';  // All in one string 
st  += typeof(ary2) + " " + ary2.length + " " + ary2 + '\n'; 
st  += (ary1[0]==ary2[0])+'\n';
st  += (ary1==ary2);

console.log(st);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Result:
object 3 d,e,f
object 3 d,e,f
true
false

Why Same yet different? Curious minds inquire!

Answer №1

The == operator checks if two objects are the same by comparing their references. It does not consider the content of the objects. Even if you deep clone an array to create a new array, the two arrays will still be considered different.

For example:

Person person1 = new Person("1", "Thomas", "Meier");
Person person2 = new Person("1", "Thomas", "Meier");
Person person3 = person1;

System.out.println(person1 == person2);
// Output: false
System.out.println(person1 == person3);
// Output: true

Answer №2

The reason for this behavior is that arrays in JavaScript are compared based on their references. Each time you create an array, it gets assigned a unique reference. So when you try to compare two arrays, JavaScript actually compares their references rather than their actual values.

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

The initial JSON value stored in the Laravel Database

I am currently handling form data to be saved into the database, but facing an issue where the first record is being duplicated multiple times during the saving process. return response()->json($request->all()); JSON ... I am encountering difficult ...

Tips on sorting a struct array with qsort

Tasked with the challenge of retrieving a binary file, reading it into an array comprised of structs and sorting it based on a specific array within each struct has proven to be quite the hurdle. At this moment in time, my main struggle lies within the rea ...

Challenges faced with Vuetify's vertical and non-linear stepper components

I've been struggling to grasp the concept of Vuetify's stepper feature. Despite my efforts, I haven't been successful in combining different steppers from their page that each have elements I need but lack others. One example is this one on ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...

The refusal to run JavaScript stemmed from an empty MIME type, resulting from the combination of nodeJS, express, engintron, and nginx

Currently, I'm struggling with a frustrating issue that's making me want to pull my hair out. So, here's some important information you need to be aware of: My application is built using node.js (version 16.13.1) with express and nginx man ...

What sets canvas and webgl renderer apart in the world of three.js?

Attempting to showcase a sphere using three.js, but encountering issues when rendering with canvasRenderer due to the appearance of grey lines on the sphere. View the code here: http://jsfiddle.net/jzpSJ/ See the screenshot here: However, when rendering ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

What are the steps to implement server side routing using react-router 2 and expressjs?

If you're looking to delve into server side rendering with react-router, the documentation linked here might fall short in providing a comprehensive understanding. In particular, it may not offer enough insights on how to leverage react-router 2 for r ...

How to smoothly glide to the bottom of a chat box by scrolling synchronously

I am currently in the process of developing a chat application. Each time a user sends a new message, it is added to a list of messages displayed in an unordered list (ul). I have successfully made the ul scrollable, but unfortunately, when a new message i ...

A guide to updating property values in an array of objects in JavaScript while ensuring they remain in consecutive order

I am dealing with an array of objects called list. The parameters rid and rorder are provided for processing. -> 1. Whenever the value of rid matches the id in the list, the itemorder is updated with the value of rorder. -> 2. In the updated list p ...

Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head." I have successfully implemented the show/hide functionalit ...

What steps are involved in generating the JSON Array string shown below?

Looking for assistance on creating and sending a JSON Array string, here is an example of what I need: I am utilizing the JSON Framework, which can parse JSON array but I'm unsure how to create a JSON Array. { "deferred": [ { "API": "Test1" ...

Go back to the previous selection in the Select field if the JavaScript Confirm function returns a false value

I am dealing with an HTML select field that has one option pre-selected. Whenever another option is selected, a change event is triggered which displays a confirmation prompt. What I am trying to achieve is, if the user cancels the confirmation (i.e., if ...

What is the best way to change the date format from "yyyy-MM-dd" in a JavaScript file to "dd/MM/yyyy" and "MM/dd/yyyy" formats in an HTML file?

Is there a way to transform the date string "2020-08-02" from a JavaScript file into the formats "08/02/2020" and "02/08/2020" in an html file, without relying on the new Date() function in JavaScript? I would greatly appreciate any assistance with this t ...

Encountered an issue while trying to read properties of undefined (specifically 'meta') within a Vue 3 single-spa application

I've been working on a micro-frontend project, utilizing vue 3 and single-spa 5.9.3. Recently, I attempted to update one of the npm packages for a Micro-frontend to the latest release. The build process went smoothly, but it resulted in the following ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Issue occurred: The error "Undefined offset 1" was encountered while trying to upload a file via

Every time I try to pass data into my file upload controller, I keep encountering an error message that says undefined offset: 1. function TestFileUpload() { $i=0; if(!isset($_FILES[$i]) ) { echo "No file is being uploaded"; } el ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

Spacing issues with inline-block elements when dealing with a large quantity of items

Currently, I am tackling the JS/jQuery Project for The Odin Project and I am confident that my solution is working exceptionally well. However, the issue I am facing is that when dealing with larger amounts of elements (around 40-45 in JSFiddle and 50-52 ...

Setting the initial viewer position in Panolens: A step-by-step guide

I've been working on setting the initial viewer position for panolens.js for a while now. Here's how the set-up looks: const panoPhoto1 = 'https://conceptcityiasi.ro/assets/images/tours/tip1/apartamente-noi-de-vanzare-iasi-dacia-1_camera-ti ...