Skip to content

Instantly share code, notes, and snippets.

@nelsonfncosta
Created April 20, 2021 16:20
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 nelsonfncosta/1b51f95c76c21fb3aae71142c5ccd5ac to your computer and use it in GitHub Desktop.
Save nelsonfncosta/1b51f95c76c21fb3aae71142c5ccd5ac to your computer and use it in GitHub Desktop.
Example of how closures can help with memory management
function findCustomerCity(name) {
const texasCustomers = ['John', 'Ludwig', 'Kate'];
const californiaCustomers = ['Wade', 'Lucie','Kylie'];
return texasCustomers.includes(name) ? 'Texas' :
californiaCustomers.includes(name) ? 'California' : 'Unknown';
};
// For every call, memory is unnecessarily re-allocated to the variables texasCustometrs and californiaCustomers .
function findCustomerCity() {
const texasCustomers = ['John', 'Ludwig', 'Kate'];
const californiaCustomers = ['Wade', 'Lucie','Kylie'];
return name => texasCustomers.includes(name) ? 'Texas' :
californiaCustomers.includes(name) ? 'California' : 'Unknown';
};
let cityOfCustomer = findCustomerCity();
cityOfCustomer('John');//Texas
cityOfCustomer('Wade');//California
cityOfCustomer('Max');//Unknown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment