I'm learning JavaScript Proxy .
By using set trap i only want to add even number to Array. But every time throw
Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'length'
Here is my code example.
//Only even numbers will be added here. We are using Js Proxy
let evenNumbers = [];
evenNumbers = new Proxy(evenNumbers, {
set(target, p, value, receiver) {
if ( (value % 2) === 0 ) {
target[p] = value;
return true
}else {
return false;
}
}
});
evenNumbers.push(2);
You neet to return
true
for both cases, becausepush
calls the proxy twice, one by pushing the value and another times to change thelength
property. To avoid unnecessary more action whithin in this proxy, you could exit early with this unwanted property.