How to Use the JavaScript Class Contains Method?

Estimated read time 1 min read

JavaScript does not have a built-in contains method for classes, but you can add one to the Array class. The Array.prototype.includes() method is similar to a contains method and can be used to check if an array contains a particular element. Here’s an example:

let array = [1, 2, 3, 4, 5];
console.log(array.includes(3)); // Output: true
console.log(array.includes(6)); // Output: false

In this example, the includes method is called on the array object and is passed the argument 3. Since 3 is present in the array, the method returns true.

If you need to add a contains method to the Array class, you can do so by adding a new method to the Array.prototype object:

Array.prototype.contains = function(element) {
  return this.includes(element);

let array = [1, 2, 3, 4, 5];
console.log(array.contains(3)); // Output: true
console.log(array.contains(6)); // Output: false

In this example, we’ve added a new method contains to the Array.prototype object. This method simply calls the built-in includes method and returns its result. Now, you can use the contains method on any array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply