Blog>
Snippets

Automatic Property Initialization with Proxy

Implement a pattern where a Proxy automatically initializes properties to default values when they are first accessed.
const defaultValues = {
  name: 'Unknown',
  age: 0,
  location: 'Unknown'
};

const autoInitProxyHandler = {
  get(target, property) {
    if (!(property in target)) {
      target[property] = defaultValues[property] || null;
    }
    return target[property];
  }
};

const user = new Proxy({}, autoInitProxyHandler);

console.log(user.name);     // Outputs 'Unknown'
console.log(user.age);      // Outputs 0
console.log(user.location); // Outputs 'Unknown'
console.log(user.email);    // Outputs null, as email is not in defaultValues
This code initializes a Proxy with a handler that automatically assigns default values to properties when they are first accessed. It uses a defaultValues object to store predefined default values for certain properties. Whenever a property is accessed, the handler checks if the property exists on the target object, and if not, it initializes it with a default value from defaultValues or null if not specified.