Skip to content

Instantly share code, notes, and snippets.

@simeg

simeg/fp_js_2.js Secret

Created May 22, 2022 14:42
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 simeg/ecd4d49bb8de8d86ca8bf1a93763af3a to your computer and use it in GitHub Desktop.
Save simeg/ecd4d49bb8de8d86ca8bf1a93763af3a to your computer and use it in GitHub Desktop.
FP in JS 2
// Create a person with a name
let simon = {"name": "simon"};
// Instead of copying simon, we assign it by reference.
// This is dangerous and can have unwanted behavior later.
let lisa = simon;
// Set the correct name of lisa
lisa.name = "lisa";
// But now we also updated simon's name!
console.log(simon); // { name: 'lisa' }
// If we would have copied simon, this would not have happened
// Let's see how we would do it in functional programming
let beth = {"name": "beth"};
// Copy beth instead of using a reference to it
let andy = {...beth};
// Set the correct name of andy
andy.name = "andy";
// Now both variables have the correct name
console.log(andy); // { name: 'andy' }
console.log(beth); // { name: 'beth' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment