Javascript - Collection Proxy has


Proxy has is used to trap "in" operator.

has is useful to hide a particular property of an object.

We can return false even if the property is present on an object.

The following code hides beer inventory from the restaurant object using the has method to trap "in" operator.


const restaurant = { 
    soda: 5, /*from  ww w. j a  v a 2  s  . c o  m*/
    beer: 10 
const restHandler = { 
    has: function(target, property) { 
        if (property === "beer") { 
            return false; 
        return property in target; 

const restProxy = new Proxy(restaurant, restHandler); 
console.log("beer" in restProxy);    // false 
console.log("soda" in restProxy);    // true


Here, all "in" operator invocations are trapped in the "has" method.

If the property name is "beer," false is returned; otherwise the default behavior is maintained (check property in target).

A "has" can only help you in preventing the detection of a particular property from "in" operator.

The property is still enumerable and can be accessed via a loop.

Related Topic