Copying values seems somewhat trivial. Nevertheless, it’s almost impossible to find a developer that has never had an issue with some wrong reference, or pointer in the case of C-like languages. In this article, I’m going to focus on how to copy variables/values in JavaScript.
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. They are the following:
Primitive values are immutable — instead of changing them directly, we’re modifying a copy, without affecting the original. **They are passed by value. **They’re assigned to variables and passed into functions by copying their value.
let example = '0';
let example_copy = example;
example = '1';
console.log('example'); // '1'
console.log('example_copy'); // '0'
Reference values, objects, and arrays, which are a special type of an object, are a bit different. Contrary to primitives these are mutable. This means they have properties that we can access and change
**They are passed by reference and no copies are made before passing them. **This article is focused on these and different ways of copying them.
Shallow copy means we just pass just the reference meaning only the memory addresses are copied.
Let’s create a basket object indicating we have 1 keyboard and 2 monitors as default values and trying to copy it.
let basket = { keyboard: 1, monitor: 2 };
let basketShallow = basket;
basket.keyboard = 3;
console.log(basket); // { keyboard: 3, monitor: 2 }
console.log(basketShallow); // { keyboard: 3, monitor: 2 }
Notice that the basket_shallow.keyboard value has changed. This happened because the value was copied by the reference and changing in one place will change for all variables sharing that object reference.
#javascript #coding #programming #deep-copy #shallow-copy