Last active
February 20, 2023 07:26
-
-
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
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
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