JavaScript Set isSubsetOf()
Syntax & Examples

Set.isSubsetOf() method

The isSubsetOf() method of the Set object in JavaScript takes another set as an argument and returns a boolean indicating if all elements of the original set are contained in the given set.


Syntax of Set.isSubsetOf()

The syntax of Set.isSubsetOf() method is:

isSubsetOf(other)

This isSubsetOf() method of Set takes a set and returns a boolean indicating if all elements of this set are in the given set.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe set to compare with the original set.

Return Type

Set.isSubsetOf() returns value of type boolean.



✐ Examples

1 Using isSubsetOf() to check if a set of numbers is a subset

In JavaScript, we can use the isSubsetOf() method to check if a set of numbers is a subset of another set.

For example,

  1. Create a new Set object setA with initial values 1 and 2.
  2. Create another Set object setB with initial values 1, 2, and 3.
  3. Use the isSubsetOf() method to check if setA is a subset of setB.
  4. Log the result to the console using console.log().

JavaScript Program

const setA = new Set([1, 2]);
const setB = new Set([1, 2, 3]);
const isSubset = setA.isSubsetOf(setB);
console.log(isSubset);

Output

true

2 Using isSubsetOf() to check if a set of strings is a subset

In JavaScript, we can use the isSubsetOf() method to check if a set of strings is a subset of another set.

For example,

  1. Create a new Set object setA with initial values 'apple' and 'banana'.
  2. Create another Set object setB with initial values 'apple', 'banana', and 'cherry'.
  3. Use the isSubsetOf() method to check if setA is a subset of setB.
  4. Log the result to the console using console.log().

JavaScript Program

const setA = new Set(['apple', 'banana']);
const setB = new Set(['apple', 'banana', 'cherry']);
const isSubset = setA.isSubsetOf(setB);
console.log(isSubset);

Output

true

3 Using isSubsetOf() to check if a set of objects is a subset

In JavaScript, we can use the isSubsetOf() method to check if a set of objects is a subset of another set of objects.

For example,

  1. Create a new Set object setA with initial objects representing different people.
  2. Create another Set object setB with additional objects representing different people.
  3. Use the isSubsetOf() method to check if setA is a subset of setB.
  4. Log the result to the console using console.log().

JavaScript Program

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const setA = new Set([person1]);
const setB = new Set([person1, person2]);
const isSubset = setA.isSubsetOf(setB);
console.log(isSubset);

Output

true

Summary

In this JavaScript tutorial, we learned about isSubsetOf() method of Set: the syntax and few working examples with output and detailed explanation for each example.