Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of pass by value in JavaScript.
/* Pass By Value */
const obj = { test: "My String", stat: 300 };
const testList = [{ stat: 3 }, { stat: 5 }, { stat: 20 }, { stat: 80 }];
/* Original Values */
console.log(obj);
console.log(testList);
const newList = testList.slice(); //Copy the list
newList[2].stat = 45;
console.log(testList); //Test List has been changed completely
/* Example Solution */
const newTestList = [{ stat: 3 }, { stat: 5 }, { stat: 20 }, { stat: 80 }];
const copy = JSON.parse(JSON.stringify(newTestList.slice()));
copy[2].stat = 999;
/* Works and preserves both lists */
console.log(newTestList);
console.log(copy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment