Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Created July 13, 2017 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KinoAR/c18ffd97aec718e286edc6b7dfc2265c to your computer and use it in GitHub Desktop.
Save KinoAR/c18ffd97aec718e286edc6b7dfc2265c to your computer and use it in GitHub Desktop.
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