-1

function ngOnInit() {
  let ref1 = {
    foo: 'bar'
  };
  let ref2 = ref1;
  ref2 = null;
  console.log(ref1, ref2);
}

ngOnInit();

I would expect to see ref1 and ref2 both equal to NULL but they are not. In the console they report

ref1: Object { foo: "bar" }

ref2: null

is this expected? If so how do I pass by reference?

Clint
  • 973
  • 7
  • 18
  • 7
    You *are* passing it by reference but here you are changing what `ref2` points to. That does not change the state of the assigned instance that `ref1` points to. As a test change the line `ref2 = null;` to this `ref2.foo = null;`, what does your console display now? – Igor Dec 12 '19 at 21:00
  • why was this voted down exactly? i provided code and a good explanation of what was my issue was. – Clint Dec 12 '19 at 21:13
  • 1
    @Clint there is nothing even slightly related to Angular in this question, only basic JavaScript, nor is there any objects being passed - just references to objects being reassigned; of course you may not have known those things but it does make it (unintentionally) a misleading and poorly-formed question – Klaycon Dec 12 '19 at 21:25
  • Does this answer your question? [JavaScript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – Zze Dec 12 '19 at 21:27
  • There’s a common misconception that Javascript is pass-by-value sometimes and pass-by-reference when dealing with non-primitives. The reality is that Javascript is **always** pass-by-value, only that when dealing with non-primitives the value IS a reference. When you set `ref2` to `null`, you’re simply overwriting its *value*, which has no effect on `ref1`’s *value* nor the object that that *value* just happens to be a reference to. – Lennholm Dec 12 '19 at 21:35
  • @Lennholm Indeed, this misconception is not just for JavaScript but most modern languages - in general "pass by reference" has come to mean "pass by a value which is a reference", see [this question](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) for more – Klaycon Dec 12 '19 at 21:40

1 Answers1

4

This is unrelated to Angular... it's just how JavaScript works. You've overwritten ref2's reference to the object. This does not also overwrite ref1's reference to the object.

Instead, change a property of the object referred to by ref2 and see that the change also happens to the object referred to by ref1... because they both reference the same object.

function ngOnInit() {
  let ref1 = {
    foo: 'bar'
  };
  let ref2 = ref1;
  ref2.foo = 'baz';
  console.log(ref1, ref2);
}

ngOnInit();

This would result in:

ref1: Object { foo: "baz" }

ref2: Object { foo: "baz" }

Aaron Cicali
  • 1,496
  • 13
  • 24