0

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?

ray
  • 26,557
  • 5
  • 28
  • 27
  • 4
    Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Anurag Srivastava Oct 22 '21 at 17:55
  • Objects in JavaScript are copied by reference. In order to duplicate them there are several methods, depending on the complexity of the object. In this case, using `assign` should fit. Use `array.push(Object.assign({}, object))` to add a cloned object to the array. – Gil Oct 22 '21 at 18:59

1 Answers1

1

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);
Shivam Gupta
  • 159
  • 6