0

Javascript Im just curious to know as we move a to a.next and b to b.next as the objects are copied by address why headA and headB don't change

headA - >HEAD OF 1ST linked list headB - >HEAD OF 2nd linked list

var getIntersectionNode = function(headA, headB) {
   let a = headA, b = headB;
    while (a !== b) {
        console.log(headB, '=========headb=========');
        console.log(headA, "----------heada==========");
        a = !a ? headB : a.next
        b = !b ? headA : b.next
    }
    return a    
};

whereas when we make object assign to another value and change it original also change ?

var a = 10;
b =a ;
console.log(a,b);

 

var a = {
    "name" :"A"
}

b =a;

b.name = "C";

console.log(a,b);
amit
  • 51
  • 5
  • Where do you expect `headA` or `headB` to be changed? – jabaa Feb 03 '23 at 15:18
  • as a change its location so should head @jabaa ? – amit Feb 03 '23 at 15:18
  • These are references, not pointers. You change what the reference is pointing to, not the data in memory at the address – Konrad Feb 03 '23 at 15:19
  • Why? `a` and `headA` are two different variables. Why would `a = ...` change `headA`? There are no "real" references in JavaScript, like e.g. in C++. – jabaa Feb 03 '23 at 15:19
  • 1
    a and b are variables on the "getIntersectionNode" function call stack, all you're doing is assigning new values to them. There's no way in JS to dereference a pointer and assign a different value to whatever headA or headB point at. – Anton Podolsky Feb 03 '23 at 15:20
  • var a = 15; b =a if i change b =13 the a also change ?@jabaa – amit Feb 03 '23 at 15:21
  • No, it doesn't change `a`. You get `a === 15` and `b === 13`. – jabaa Feb 03 '23 at 15:21
  • var a = 10; var b =13; b =a ; console.log(a,b); @jabaa – amit Feb 03 '23 at 15:22
  • `b = a` overwrites `b`. It's equivalent to `b = 10`. I don't understand your point. – jabaa Feb 03 '23 at 15:23
  • @jabaa references in c++ work a similar way as in javascript. Pointers on the other hand work differently – Konrad Feb 03 '23 at 15:23
  • 1
    @Konrad There are no references in JavaScript. In C++ you have `int a = 10; int &b = a; b = 13;`. This will change `a`. It's impossible in JavaScript. In JavaScript you get `let a = 10; let b = a; b = 13; a === 10`. `b` isn't a reference to `a`. – jabaa Feb 03 '23 at 15:24
  • @amit you change the object not, the variable in the example, there is a difference – Konrad Feb 03 '23 at 15:27
  • @Konrad can you answer it i have my few edits how 3 examples are different – amit Feb 03 '23 at 15:27
  • @jabaa you are right, I thought it's working like java :) – Konrad Feb 03 '23 at 15:29
  • @jabaa could you please explain in answer what is happening in question for 3 cases ? – amit Feb 03 '23 at 15:31
  • TLDR; `a` and `headA` are values, that contain references. An assignment overwrites and copies these values. – jabaa Feb 03 '23 at 15:36

0 Answers0