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)); // falseThe 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')); // trueChallenge
EasyCreate 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)); // falseThe 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')); // trueTry it yourself
function symmetricDifference(arr1, arr2) {
// Write your code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys