0

Now, say for example I write:

let object1 = {a: true}
let object2 = object1

object1.a = false

console.log(object1)
console.log(object2)

The result of the code above is as you'd expect:

{a: false}
{a: false}

But if I assigned object1 to say a string or number, anything that isn't a data structure, it doesn't give the same result, here's what I mean:

let object1 = 'Hello'
let object2 = object1

object1 = 'Hello World'

console.log(object1)
console.log(object2)

this is the result that follows:

'Hello World'
'Hello'

I've tried the first case with arrays and sets and the second one with numbers and I also replicated this with Python as well. Can anyone please explain why example 2 doesn't work the same way example 1 does?

Is there a difference in the way data structures vs strings and numbers are stored in memory.?

I just don't really know honestly, lol!

Sunkanmi
  • 7
  • 2
  • 2
    What is with all these tags? Why `python`, `pointers`, `memory`, `data-structures`? – Andreas Mar 27 '21 at 08:30
  • `object1 = 'Hello World'` doesn't mutate the object, `object1.a = false` does. If you did `object1 = {a: false}` and then did `console.log(object1); console.log(object2);` you'd see the same behavior – juanpa.arrivillaga Mar 27 '21 at 08:51
  • In CPython, at least, **no** there is no difference in the way objects are treated in memory. – juanpa.arrivillaga Mar 27 '21 at 08:52

0 Answers0