Menu
Coddy logo textTech

Checking If An Element Exists

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 32 of 65.

To check if an element exists in a Set, use the has() method. This method returns true if the element is in the Set, and false otherwise.

Here's how to use the has() method:

const mySet = new Set([1, 2, 3, 4, 5]);

console.log(mySet.has(3)); // true
console.log(mySet.has(6)); // false

The has() method is useful when you need to check for the existence of an element before performing operations on it:

if (mySet.has(3)) {
  console.log("3 is in the set");
} else {
  console.log("3 is not in the set");
}

Remember that Sets use strict equality (===) for comparisons, so 5 and '5' are considered different elements:

const mixedSet = new Set([1, '2', 3]);

console.log(mixedSet.has('1')); // false
console.log(mixedSet.has(2));  // false
console.log(mixedSet.has('2')); // true
challenge icon

Challenge

Easy

Create a function called symmetricDifference that takes two arrays as parameters. The function should convert the arrays to sets, and return a new Set containing elements that are in either of the two Sets, but not in both. Use the has() method to check for element existence. Finally convert the set to an array and return it.

Cheat sheet

To check if an element exists in a Set, use the has() method. This method returns true if the element is in the Set, and false otherwise.

const mySet = new Set([1, 2, 3, 4, 5]);

console.log(mySet.has(3)); // true
console.log(mySet.has(6)); // false

The has() method is useful for conditional operations:

if (mySet.has(3)) {
  console.log("3 is in the set");
} else {
  console.log("3 is not in the set");
}

Sets use strict equality (===) for comparisons:

const mixedSet = new Set([1, '2', 3]);

console.log(mixedSet.has('1')); // false
console.log(mixedSet.has(2));  // false
console.log(mixedSet.has('2')); // true

Try it yourself

function symmetricDifference(arr1, arr2) {
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow