DEV Community

Discussion on: 8 Ridiculously Simple Javascript Tricks Not Taught on Tutorials

Collapse
 
amitcoditas profile image
Amit Thakkar

for validations, do explore object proxies.

developer.mozilla.org/en-US/docs/W...

let validator = {
  set: function(obj, prop, value) {
    if (prop === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError('The age is not an integer');
      }
      if (value > 200) {
        throw new RangeError('The age seems invalid');
      }
    }

    // The default behavior to store the value
    obj[prop] = value;

    // Indicate success
    return true;
  }
};

const person = new Proxy({}, validator);

person.age = 100;
console.log(person.age); // 100
person.age = 'young';    // Throws an exception
person.age = 300;        // Throws an exception
Collapse
 
veebuv profile image
Vaibhav Namburi

Proxies are not talked about enough!

Thanks for this!

Some comments have been hidden by the post's author - find out more