Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.
but why?

What I have tried:

JavaScript
var func= new function () {
         var A = [20, 30, 25, 5, 3, 2];
         var B = A;

         for (var i = 0; i <= A.length - 1; i++) {
             if (A[i] > A[i+1]) {
                 var tmp = A[i];
                 A[i] = A[i + 1];
                 A[i + 1] = tmp;
             }
         }

             var big = A[A.length-1];
             var index = 0;

             for (var j = 0; j <= B.length-1; j++) {
                 if (big == B[j])
                 {
                     index = j;
                     break;
                 }
             }
             console.log(A);
             console.log(B);
             return (index);
     };
Posted
Updated 10-Feb-23 1:07am

Simple: it's the same array.
JavaScript
var A = [20, 30, 25, 5, 3, 2];
var B = A;

Creates A and "points" it at an array of values, then creates B and copies the "pointer" from A to B, so they both refer to the same locations in memory. Hence, any change to the data via A will also change the data if you access it via B
To get a copy of the array data, use the slice[^] function:
JavaScript
var A = [20, 30, 25, 5, 3, 2];
var B = A.slice();
 
Share this answer
 
Because so the language works. The alternative would be to copy the other object on assignment, for example, after
var B = A;
B would reference a copy of (the object referenced by) A and the two objects would have been independent (this is how, for instance structs behave in C/C++ programming languages).

Please note, such alternative would be 'expensive' and you may always obtain the same result by explicitely copying the object (in your case the array).
 
Share this answer
 
you may use spread operator ... B=[...A]. it will not affect the A values
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900