JavaScript Set isDisjointFrom()
Syntax & Examples
Set.isDisjointFrom() method
The isDisjointFrom() method of the Set object in JavaScript takes another set as an argument and returns a boolean indicating if the original set has no elements in common with the given set.
Syntax of Set.isDisjointFrom()
The syntax of Set.isDisjointFrom() method is:
isDisjointFrom(other)
This isDisjointFrom() method of Set takes a set and returns a boolean indicating if this set has no elements in common with the given set.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | The set to compare with the original set. |
Return Type
Set.isDisjointFrom() returns value of type boolean
.
✐ Examples
1 Using isDisjointFrom() to check if two sets of numbers are disjoint
In JavaScript, we can use the isDisjointFrom()
method to check if two sets of numbers have no elements in common.
For example,
- Create a new Set object
setA
with initial values 1, 2, and 3. - Create another Set object
setB
with initial values 4 and 5. - Use the
isDisjointFrom()
method to check ifsetA
andsetB
are disjoint. - Log the result to the console using
console.log()
.
JavaScript Program
const setA = new Set([1, 2, 3]);
const setB = new Set([4, 5]);
const isDisjoint = setA.isDisjointFrom(setB);
console.log(isDisjoint);
Output
true
2 Using isDisjointFrom() to check if two sets with common elements are disjoint
In JavaScript, we can use the isDisjointFrom()
method to check if two sets that have common elements are not disjoint.
For example,
- Create a new Set object
setA
with initial values 'apple', 'banana', and 'cherry'. - Create another Set object
setB
with initial values 'banana' and 'cherry'. - Use the
isDisjointFrom()
method to check ifsetA
andsetB
are disjoint. - Log the result to the console using
console.log()
.
JavaScript Program
const setA = new Set(['apple', 'banana', 'cherry']);
const setB = new Set(['banana', 'cherry']);
const isDisjoint = setA.isDisjointFrom(setB);
console.log(isDisjoint);
Output
false
3 Using isDisjointFrom() to check if two sets of objects are disjoint
In JavaScript, we can use the isDisjointFrom()
method to check if two sets of objects have no elements in common.
For example,
- Create a new Set object
setA
with initial objects representing different people. - Create another Set object
setB
with different objects representing different people. - Use the
isDisjointFrom()
method to check ifsetA
andsetB
are disjoint. - Log the result to the console using
console.log()
.
JavaScript Program
const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const person3 = { name: 'Doe' };
const setA = new Set([person1]);
const setB = new Set([person2, person3]);
const isDisjoint = setA.isDisjointFrom(setB);
console.log(isDisjoint);
Output
true
Summary
In this JavaScript tutorial, we learned about isDisjointFrom() method of Set: the syntax and few working examples with output and detailed explanation for each example.