Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active February 20, 2023 07:26
Show Gist options
  • Save r3dm1ke/865c1430338a268d926cfdfaf811ef37 to your computer and use it in GitHub Desktop.
Save r3dm1ke/865c1430338a268d926cfdfaf811ef37 to your computer and use it in GitHub Desktop.
Using the Proxy API to set a default value for undefined object properties
const defaultValueHandler = {
get: (obj, property) =>
property in obj ? obj[property] : 'general kenobi'
}
const objectWithDefaultValue = new Proxy({}, defaultValueHandler);
objectWithDefaultValue.a = 'b';
console.log(objectWithDefaultValue.a); // b
console.log(objectWithDefaultValue['hello there']); // general kenobi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment