Mutability , Immutability ,use of Object.assign

var list={element:"1",next:{element:"2",next:null}}

var current=list
current.next.next={element:"3",next:null}
current.next.next.next={element:"4",next:null}
console.log(JSON.stringify(current))

console.log(JSON.stringify(list))

I wrote this code myself. I don’t understand one thing how my list variable is getting updated
because
first I say

var list={element:"1",next:{element:"2",next:null}}

then I assign that value to variable current

var current=list

after that you can see on the code that I only change the value of variable current
I did not say anywhare
list=current

but when I say

console.log(JSON.stringify(current))


console.log(JSON.stringify(list))

both current and list variable look similar
below is the output we get when we use

console.log(JSON.stringify(current))


console.log(JSON.stringify(list))
 

{"element":"1","next":{"element":"2","next":{"element":"3","next":{"element":"4"
,"next":null}}}}

anybody can explain this?

see the below code

var num1=5
var num2=num1
num2=6
console.log(num1)
// produce output 5
console.log(num2)
//produce output 6

here I say

var num2=num1
// now the value of num2 is  5

then I say
I say

num2 =6
//now the value of num2 is 6
//but the value of num1 is still 5
//it did not change
// this thing I know why the value of num1 is not changed
// but the first program I wrote made me confused 
// please help me


This post should shed some light on what the issue is…

1 Like

first, please don’t include text i your code blocks it is incredibly difficult to follow what you want to say

when you are dealing with complex data structures, you will not copy the data structure with that, but you will just change the reference
I suggest you researched to copy an object

1 Like

This is not a bug…

let a = {
    foo: 'bar'
};
let b = a;
b.foo =  'test2'
console.log(b.foo); // test2
console.log(a === b) // true

What you are trying to do…

let a = {foo: "bar"};
let b = Object.assign({},a);
b.foo = "bar2"
console.log(a); // {foo: "bar"}
console.log(b);// {foo: "bar2"}
console.log(b === a) // false

Thanks for such an awesome article .

1 Like

Sorry bro. I felt its really difficult to explain code with my doubt

you can create multiple code blocks and write between them

I have edited your post to remove the text paragraphs from the code blocks, now it is easier to follow

Thank you brother …

I think Better I can rename the heading as mutability in JavaScript. So it will be useful for others also!
what do you think?

if you use descriptive titles in your posts it is much useful to who want to help and for who is searching the same topic

I should note that the preferred current approach is to use the object spread operator

let b = { ...a } == let b = Object.assign({},a)