How to check if an object has a given private attribute?

class Transformer {
  #transform() {
    console.log('Fancy sound! 🎶');
  }

  canTransform() {
    return #transform in this;
  }
}

const optimusPrime = new Transformer();
console.log(optimusPrime.canTransform()); // true
Copy

August 3rd, 2022

# Private attribute check

Add to bookmarks

We can use the in operator to check if an object has a given private property.

HomeBookmarks