0

If I write the following code:

var foo = [1, 2, 3, 4];
var bar = foo;
Object.freeze(bar);

Does this mean foo is also immutable?

If not, how can bar remain constant if foo is updated?

the8472
  • 40,999
  • 5
  • 70
  • 122
Fitzy
  • 1,871
  • 6
  • 23
  • 40
  • There is no object in your code (and all primitive values are immutable, yes). And if you did something like `foo = {}`, then there would be only one object (not a second "`bar` one"). – Bergi Aug 21 '17 at 03:06
  • 1
    note: *The object being frozen is immutable. However, it is not necessarily constant. The second example shows that a frozen object is not constant (freeze is shallow).* - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#Examples – Jaromanda X Aug 21 '17 at 03:08
  • @Bergi modified code to make my point more clear – Fitzy Aug 21 '17 at 03:10
  • @Fitzy Thanks. But yes, `Object.freeze` works on the (one!) *object* passed to it, not on the variable. – Bergi Aug 21 '17 at 03:11
  • Btw, you should be able to simply try this out. – Bergi Aug 21 '17 at 03:12
  • @Bergi I guess my question, as written in the update, is how could i change the value of `foo` without changing the value of `bar` as well? – Fitzy Aug 21 '17 at 03:14
  • @Fitzy Ah ok, that's what you wanted to know. See the third duplicate link for that :-) – Bergi Aug 21 '17 at 03:19
  • @Bergi Sure enough, it worked. Should've been more clear. Thanks :) – Fitzy Aug 21 '17 at 03:24

0 Answers0