1
votes

As someone used to python and C++, having an = copy objects by reference rather than value is not intuitive at all. Not just that, but there seems to be no direct way of copying objects to begin with. JSON.parse(JSON.stringify) is the closest option (if I know correctly), and even that has problems.

a) In a language where all variables are anyway treated as objects, why does the = operator distinguish between primitive and non-primitive data types to decide whether to copy by value or reference?

b) Why is copy by value not possible for objects?

c) What techniques are helpful for a beginner used to copying objects by value to code without it?

1
you can use Object.assign to copy js objects - Nijeesh Joshy
@NijeeshJoshy No, that only does a shallow copy - ghosts_in_the_code
In Java and C++ you have to write a copy constructor. - SPlatten
Some languages have a mechanism for deep copy but they are almost all "some assembly required". Very few provide a truly simple way of doing a deep copy. JavaScript is just one of a few that doesn't provide a standard way of doing it. In general there aren't many scenarios where a deep copy is useful in a front-end context, which is what JavaScript was originally designed for - Dan
A non-primitive is an object that the author arbitrarily describes and the language has no way of ’understanding’ its design logically. This means that because of potential problems with things like circular referencing, references to singletons, etc, the author will also have to be the one to define any deep copy functionality. This is true for all languages that allow data structures of arbitrary design. - Lennholm

1 Answers

4
votes

a) In a language where all variables are anyway treated as objects, why does the = operator distinguish [...] ?

The =(assign) operator does not distinguish between primitive and non primitive data types. It kinda does the same for both, considering that equality is preserved after assignment (excluding exceptions e.g. NaN, ...).

b) Why is copy by value not possible for objects?

Wrong assumption in a) leads to this. Assignment is no copy and a copy of an object does not preserve equality.

Or think about: var obj = {a: {b: 1}} .

What is the value of obj.a ? It is just the reference to {b:1}.

c) What techniques are helpful for a beginner used to copying objects by value to code without it?

There are many approaches for this. And two trivial cases.

As the first case one knows the layout of the object. Thus creates a template or constructor and passes all values into the corresponding properties.

As the second case one assumes a cyclic object containing everything possible in javascript (functions, regexp, symbols, undefined, ...) of depth n and builds something (not json.stringify).

For starters: possible duplicate


Assumptions:

primitive and non primitive data types have default getter,setter, ...