When I put an object into array using push method and then change the value of the object, the value of the object in the array also changes. How to prevent it?
function onLoad() {
let array = []
let object = {}
object[1] = [1,2]
array.push(object)
object[1] = [1,3]
console.log(array)
}
onLoad();
I would like the code console [{1,2}] but it will console [{1,3}].
Would anyone know how to fix this?
In JavaScript, Complex data types(Objects and arrays) are copied by reference whereas primitive data types(Strings, Numbers, and Boolean) are copied by value
Simply put , Pass by reference will not create a copy instead refer to the same memory. So original objects and arrays will be changed
Copy by value will create a copy of the value and hence original value will not be changed
function change(array1){
array1[0] = "changed";
}
var original = ["original"]
change(original)
console.log(original)
function changePrimitive(input) {
input = "changed"
}
var original = "original"
changePrimitive(original)
console.log(original);