0

I faced an issue recently:

I had an object Recipe with a primitive datatype i.e string.

export class Recipe {

    public name: string;

}

When I created an object of this type and passed it around components, every component got a new copy of this object.

I google and found in one of the answers that its because my object contains a primitive datatype and hence it can't be passed with reference and the receiver will get a copy instead.

Fair enough.

The problem is, when I created an array of objects where the object contained primitive types, I was able to share the array with all its values successfully among other components. Any change in my array was reflecting in all places where I had passed it.

Why is that an object with primitive types can not be passed as a reference but an array can?

8
  • Are you sure that it isn't being passed by reference? All JS objects, including arrays, are always passed by reference. And generally a JS will ultimately have values in it that are primitive types: array of strings, object with strings and numbers for the values, etc. How are you 'creating' that object that gets passed into components? Commented Jul 9, 2020 at 18:43
  • I am quoting it from the answer that i linked above: "Since name in NameService is a primitive type, you'll get different instance in the service and your components. When you change name in NameService, the component properties still have the initial value and the binding doesn't work as expected." Commented Jul 9, 2020 at 18:46
  • 1
    a different instance of the primitive type variable not the object that holds it. objects are always passed as reference in JS. Commented Jul 9, 2020 at 18:46
  • Correct. Everything else is passed by value. Commented Jul 9, 2020 at 18:49
  • 1
    Objects are passed by value reference, just like arrays (which are just objects with specific structure). Angular or whatever library you were using probably were just doing a shallow copy when transfering between components. When arrays are shallow copied the objects in it still hold the reference to the original object. Commented Jul 9, 2020 at 18:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.