Created
July 13, 2017 18:32
-
-
Save KinoAR/c18ffd97aec718e286edc6b7dfc2265c to your computer and use it in GitHub Desktop.
An example of pass by value in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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