Menu
Coddy logo textTech

Copy And Clear

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

Sets provide two methods for creating copies and clearing all elements:

  1. new Set(existingSet): Creates a new Set with all elements from the existing Set.
  2. clear(): Removes all elements from the Set.

Here's how to create a copy of a Set:

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

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

To clear all elements from a Set:

const mySet = new Set([1, 2, 3, 4, 5]);
console.log(mySet.size); // 5

mySet.clear();
console.log(mySet.size); // 0
challenge icon

Challenge

Easy

Create a function called setOperations that takes an array as a parameter. The function should convert the array to a set and:

  1. Create a copy of the input Set
  2. Add the number 10 to the copied Set
  3. Clear the original Set
  4. Return an object with two properties: copiedSet (the modified copy) and originalSet (the cleared original Set)

Cheat sheet

To create a copy of a Set, use the Set constructor with the existing Set:

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

To remove all elements from a Set, use the clear() method:

const mySet = new Set([1, 2, 3, 4, 5]);
mySet.clear(); // Set is now empty

Try it yourself

function setOperations(inputArr) {
  const inputSet = new Set(inputArr);
  // Write your code here
  
  
  return {
    copiedSet: copiedSet,
    originalSet: inputSet
  };
}
quiz iconTest yourself

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

All lessons in Logic & Flow