A clone is not a formally defined term in JavaScript, but in general it is well understood as a copy of a value.
In JavaScript copies can be of two kind i.e, copy by value and copy by reference. All non-primitive types are copies by references meaning any update on them will reflect in any copies at the same times.
Let’s take a small example before tackling the problem statement.
In above example:
Updating the value of msg2, does not affect msg1 since they were copied by value.
Updating the value of obj1, did not affect obj2 since they were copied by reference, i.e they hold same reference on the memory.
We have a implement a utility called deepClone, which can create copy of a value by removing any references on them. Consider only JSON serializable values as input.
In the above implementation we also considered JSON serializable values. In this particular case we need to clone all possible data types in JavaScript as much as possible mainly: Date, Map, Set, Symbol, RegExp and BigInt
The implementation remains almost the same here, we just need to handle the new cases explicitly.
You may have noticed a utility function called getTypeof which I used above. As the typeof operator is unreliable here, the new utility helps us get the actual type of input correctly as a string.