Menu
Coddy logo textTech

Adding An Element

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

To add an element to a Set, use the add() method. This method adds the element to the Set if it's not already present. If the element already exists, the Set remains unchanged.

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

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);

console.log(mySet); // Set(3) { 1, 2, 3 }

You can chain multiple add() calls. This works because add() returns the Set itself, allowing you to call add() again immediately on the result:

mySet.add(4).add(5).add(6);

console.log(mySet); // Set(6) { 1, 2, 3, 4, 5, 6 }

If you try to add a duplicate value, the Set will ignore it:

mySet.add(1);

console.log(mySet); // Set(6) { 1, 2, 3, 4, 5, 6 } (unchanged)
challenge icon

Challenge

Easy

Create a function called addUniqueElements that takes two parameters: an array and another array. The function should convert the first array to a Set, and add all elements from the second array to the Set, but only if they don't already exist in the Set. Finally convert the set to an array and return it.

Cheat sheet

To add an element to a Set, use the add() method:

const mySet = new Set();
mySet.add(1);
mySet.add(2);
console.log(mySet); // Set(2) { 1, 2 }

You can chain multiple add() calls:

mySet.add(3).add(4).add(5);
console.log(mySet); // Set(5) { 1, 2, 3, 4, 5 }

Sets automatically ignore duplicate values:

mySet.add(1); // Already exists, Set remains unchanged
console.log(mySet); // Set(5) { 1, 2, 3, 4, 5 }

Try it yourself

function addUniqueElements(array1, array2) {
  // 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