Small Group Tutorials

Here to help students catch up, keep up, and move ahead. Book a consultation here.

How to Master JavaScript Set in Punggol Tuition

Three learners review open books together at a classroom table, with stacks of textbooks, stationery and a whiteboard in the bright room.

A student project receives six sign-up messages, but only four different participant codes appear in them. Should the display say six participants or four? This is a lovely small JavaScript problem for a Punggol learner because it makes the meaning of “different” matter before any sophisticated code is needed.

JavaScript Set stores unique values and provides membership operations such as add(), has() and delete(). It can represent which fictional participant codes have appeared, while an array retains the complete sequence of messages. A Set answers whether a value is present; it does not automatically retain how often it appeared or prove that two equal-looking records describe the same person.

This lesson builds a fictional reading-club checker with invented codes, then uses it to explain equality, normalisation, union, intersection and changed-input tests. For a Punggol family exploring computing enrichment, the goal is a model the child can explain and verify, not a claim that JavaScript belongs in every school syllabus or that a particular tuition class provides it. Start with the question the project actually needs to answer.

Choose a chapter

Choose the membership question · 1–3
  1. Separate messages from distinct participants
  2. Add a value without creating a second copy
  3. Use has for the presence question
Understand removal and equality · 4–6
  1. Delete membership and read the result
  2. Check the equality rule, including types
  3. Understand why two records can remain distinct
Prepare and interpret values · 7–9
  1. Normalise identifiers under a visible contract
  2. Preserve event counts when they matter
  3. Read iteration order without inventing a ranking
Compare groups · 10–12
  1. Build a union with ordinary membership steps
  2. Find the intersection and the difference
  3. Compare memberships, not object references
Save, test and practise · 13–15
  1. Save a suitable representation
  2. Practise with a new membership question
  3. Keep the meaning beside the count

CHAPTER 1 OF 15 · Choose the membership question

1. Separate messages from distinct participants

Back to contents

const messages = ["P01", "P02", "P01", "P03", "P02", "P04"];
const participants = new Set(messages);
console.log(messages.length);    // 6
console.log(participants.size);  // 4
console.log([...participants]); // ['P01', 'P02', 'P03', 'P04']

The array contains every recorded message, including repetitions. The Set contains the distinct values encountered in that sequence. Neither result is inherently better; each answers a different question.

Draw six message cards and four labelled participant boxes. Place each card into its matching box. Counting cards gives messages; counting occupied boxes gives distinct codes. This makes the distinction visible before introducing methods.

The example assumes one validated code per fictional participant. In a real system, duplicate names, shared accounts or inconsistent identifiers would need their own rules. A collection can enforce value uniqueness without establishing that the values identify people correctly.

Write the report caption as “four distinct participant codes in six messages.” It is more precise than a bare number whose meaning the reader has to guess.

CHAPTER 2 OF 15 · Choose the membership question

2. Add a value without creating a second copy

Back to contents

const attending = new Set();
attending.add("P01");
attending.add("P01");
attending.add("P02");
console.log(attending.size); // 2

Adding a value already present does not add another entry. The Set models membership, not an event counter. If the project needs to count visits, use a separate counting structure.

Ask the learner to predict the size after each line: one, one, two. If they predict one, two, three, they are still applying an array-like model in which each addition necessarily creates another position.

add() returns the Set, so calls can be chained. Separate statements are easier to trace in a first lesson because each one has a visible effect or non-effect.

Do not use a Set to silently discard evidence the task requires. Repeated sign-ups might be harmless duplicates, or they might indicate a problem worth reporting. Keeping the message array lets the project distinguish those possibilities while also building a membership view.

CHAPTER 3 OF 15 · Choose the membership question

3. Use has for the presence question

Back to contents

console.log(attending.has("P01")); // true
console.log(attending.has("P99")); // false

The method returns a boolean answering whether that value is in the Set. It does not supply a record, a count or an explanation for absence.

This is a useful place to compare Set with the JavaScript Map lesson. A Map connects keys to values, such as a participant code to a message count. A Set directly represents a collection of values whose membership matters.

Choose by the question. “Is P01 in the group?” fits membership. “How many messages came from P01?” requires additional stored information. “What name belongs to P01?” requires a relationship to another value.

Parents can ask the question in ordinary language before discussing the method. The learner should be able to identify what information the chosen structure retains and what it leaves out.

CHAPTER 4 OF 15 · Understand removal and equality

4. Delete membership and read the result

Back to contents

console.log(attending.delete("P02")); // true
console.log(attending.delete("P02")); // false
console.log(attending.size);         // 1

The first deletion removes an existing value. The second finds nothing to remove. The boolean result distinguishes those cases.

Deleting a code from this Set does not erase the original message array, edit a school record or contact anybody. This is only the membership view inside the exercise. Make that scope explicit when teaching a method with an action-like name.

If a project needs an audit trail of who changed membership and why, the Set alone is not that trail. Store the relevant events separately under the actual project requirements.

As a practice task, remove an absent code and predict whether the Set's size changes. It should not. Then add the removed code again and inspect its iteration position later in the lesson. That changed condition connects deletion with insertion history.

CHAPTER 5 OF 15 · Understand removal and equality

5. Check the equality rule, including types

Back to contents

const mixed = new Set([7, "7", NaN, NaN, 0, -0]);
console.log(mixed.size); // 4
console.log(mixed.has(7));   // true
console.log(mixed.has("7")); // true

The number seven and the text string seven are different values. Repeated NaN values count as one member here, and positive and negative zero count as one member. These examples show why “unique” needs a defined equality rule.

For our club checker, participant codes are strings. A code is an identifier, not a quantity to calculate with. Keeping one type avoids a situation where a form's text code fails to match a value stored in another representation.

Do not respond by converting every input blindly. Define a boundary rule and check whether conversion preserves the identifier's meaning. Leading zeroes or letters may matter.

This chapter is a boundary check after ordinary repeated strings are understood. The child should be able to explain the four members without treating unusual numeric values as recommended participant identifiers.

CHAPTER 6 OF 15 · Understand removal and equality

6. Understand why two records can remain distinct

Back to contents

const one = {code: "P01"};
const two = {code: "P01"};
const recordSet = new Set([one, two, one]);
console.log(recordSet.size); // 2

The first and second objects contain equal-looking fields, but they are different objects. Adding the first object again does not create a third member. Object membership uses identity rather than automatically comparing every field.

If the project needs unique participant codes, explicitly project the records to codes after validating them. new Set(records.map(record => record.code)) answers a different question from new Set(records).

Projection also discards information from the membership collection. The Set of codes no longer stores each participant's other fields. Keep the original records if later reporting needs them.

Ask the learner what happens if two records share a code but disagree on another field. A Set does not resolve that disagreement. The data-import policy must decide whether to reject, review or deliberately choose a record.

CHAPTER 7 OF 15 · Prepare and interpret values

7. Normalise identifiers under a visible contract

Back to contents

function normaliseParticipant(value) {
  if (typeof value !== "string") {
    throw new TypeError("Participant code must be text");
  }
  const code = value.trim().toUpperCase();
  if (!/^P\d{2}$/.test(code)) {
    throw new RangeError("Expected P followed by two digits");
  }
  return code;
}

const raw = ["p01", " P01 ", "P02"];
const normalised = new Set(raw.map(normaliseParticipant));
console.log([...normalised]); // ['P01', 'P02']

The teaching contract accepts surrounding spaces and ignores case for these invented codes. It does not accept P1, a number or an arbitrary name. Another project can choose another format.

Normalisation can merge values. That is helpful only when the merge matches the requirement. Do not apply the same uppercase rule to passwords, case-sensitive identifiers or personal names merely because it works for this exercise.

Test accepted and rejected inputs before constructing the Set. Then the membership stage works with known values instead of carrying several interpretations of the same code.

CHAPTER 8 OF 15 · Prepare and interpret values

8. Preserve event counts when they matter

Back to contents

The message array from chapter 1 records two occurrences each of P01 and P02. The Set does not retain those frequencies. Its size of four cannot tell you whether the input had four messages or four thousand repetitions.

For a report requiring both membership and counts, keep the event input or construct a Map of counts alongside the Set. Use labels that separate those jobs: messages, participants and messageCounts.

A helpful diagnostic is to compare ['P01', 'P02'] with ['P01', 'P01', 'P02']. Both create the same membership Set, but their message totals differ. The lost distinction is deliberate, not a bug in Set.

Do not claim that a Set “removes duplicate people” unless the identifier model actually establishes that. It removes repeated values under its equality rule. The real-world interpretation belongs to the project's data contract and the evidence used to assign identifiers.

CHAPTER 9 OF 15 · Prepare and interpret values

9. Read iteration order without inventing a ranking

Back to contents

const order = new Set(["P03", "P01", "P02"]);
order.add("P01");
console.log([...order]); // ['P03', 'P01', 'P02']
order.delete("P01");
order.add("P01");
console.log([...order]); // ['P03', 'P02', 'P01']

Set iteration follows insertion order. Adding an existing member does not move it. Removing and then adding it supplies a new insertion position.

This is not alphabetical order, popularity order or a fairness ranking. If a display needs sorted codes, create an array view and sort that view explicitly.

Ask the learner to explain the two sequences through events rather than through appearance. The first code displayed is the first still-present value inserted, not automatically the most important participant.

Mathematical sets are often discussed without an ordering requirement. JavaScript's Set has an iteration contract because a program must visit values somehow. Keeping those two perspectives separate makes both the mathematics and the code easier to explain.

CHAPTER 10 OF 15 · Compare groups

10. Build a union with ordinary membership steps

Back to contents

const morning = new Set(["P01", "P02", "P03"]);
const afternoon = new Set(["P03", "P04"]);
const eitherSession = new Set([...morning, ...afternoon]);
console.log([...eitherSession]); // ['P01', 'P02', 'P03', 'P04']

The result contains codes present in either session. P03 appears once even though it belongs to both input Sets.

Trace the values from left to right. The construction encounters morning values first, then afternoon values. That determines this result's iteration order, while the membership meaning is the union of the groups.

These introductory examples use longstanding iteration and constructor operations rather than relying on newer Set-composition methods. If a project uses newer methods, check support in its actual runtime.

Change the inputs so one session is empty or both sessions contain the same members. Predict the result before running it. A union's membership should not gain an extra member just because a code appeared in both sources.

CHAPTER 11 OF 15 · Compare groups

11. Find the intersection and the difference

Back to contents

const bothSessions = new Set();
const morningOnly = new Set();
for (const code of morning) {
  if (afternoon.has(code)) bothSessions.add(code);
  else morningOnly.add(code);
}
console.log([...bothSessions]); // ['P03']
console.log([...morningOnly]);  // ['P01', 'P02']

The intersection answers who is present in both groups. The morning-minus-afternoon difference answers who is in morning but not afternoon. Difference has a direction: afternoon-minus-morning would contain P04 instead.

Write the plain-language question beside each result variable. That simple step prevents a correct loop from being attached to an incorrect report caption.

The loop visits the morning Set, so these results follow morning's iteration order. Membership correctness and display order remain separate checks.

For a transfer task, swap which input is traversed and which is tested. Ask what changes in the difference and what remains the same in intersection membership. The child should explain the relationship rather than merely predict a printed array.

CHAPTER 12 OF 15 · Compare groups

12. Compare memberships, not object references

Back to contents

function sameMembers(left, right) {
  if (left.size !== right.size) return false;
  for (const value of left) {
    if (!right.has(value)) return false;
  }
  return true;
}

console.log(sameMembers(new Set(["P01", "P02"]),
                        new Set(["P02", "P01"]))); // true

Two separate Set objects are not made identical objects merely because their members match. This function asks a membership question explicitly and ignores iteration order.

It assumes both inputs are Sets and uses their own equality rules for values. If they contain separate equal-looking objects, object identity still matters. The function is not a deep record-comparison system.

A report may require membership equality, order equality or both. State which one is being tested. Comparing JSON arrays of values can accidentally make order part of a test that was intended to ignore it.

The learner should create a counterexample for each requirement: same members in a different order, and different members with the same size.

CHAPTER 13 OF 15 · Save, test and practise

13. Save a suitable representation

Back to contents

const savedText = JSON.stringify([...participants]);
const loadedValues = JSON.parse(savedText);
const restoredParticipants = new Set(
  loadedValues.map(normaliseParticipant)
);
console.log(sameMembers(participants, restoredParticipants)); // true

This round trip is suitable for our validated string codes. A plain Set does not automatically export its values through ordinary JSON serialization, so the array representation is deliberate.

Parsed JSON is not automatically trusted participant data. An actual import should check that the outer value is an array before calling map, validate each item and handle errors visibly. The example's saved text was created from our known Set.

Do not generalise the round trip to every possible JavaScript value. Object identity and values that JSON cannot preserve require additional decisions.

Ask what the saved representation must retain: here, the code values and their order are available, while the membership checker itself is reconstructed. The Set's methods are not pieces of data stored in the text.

CHAPTER 14 OF 15 · Save, test and practise

14. Practise with a new membership question

Back to contents

Suppose one fictional group contains P02, P04 and P05, while another contains P01, P04 and P05. Predict their union, intersection and each directional difference.

Union membership is P01, P02, P04 and P05. The loop or constructor determines the iteration order used to display it. Intersection contains P04 and P05. The first group minus the second contains P02; the second minus the first contains P01.

Now add repeated input messages and inconsistent spaces before normalisation. Explain which change affects membership and which only changes event frequency. Try an invalid code and check that it is rejected rather than silently converted into a participant.

For a final diagnostic, build two equal-looking record objects for P04. Explain why a Set of those objects has two members while a Set of their validated code strings has one. That answer connects the collection rule to the project's chosen identity model.

The same count does not prove the same group

Imagine an expected group of P01, P02 and P03, but submitted codes P01, P02 and P99. Both groups have three members. A size-only check says nothing about the missing P03 or the unexpected P99.

const expectedGroup = new Set(["P01", "P02", "P03"]);
const submittedGroup = new Set(["P01", "P02", "P99"]);
const missingCodes = [...expectedGroup].filter(
  code => !submittedGroup.has(code)
);
const unexpectedCodes = [...submittedGroup].filter(
  code => !expectedGroup.has(code)
);
console.log(missingCodes);    // ['P03']
console.log(unexpectedCodes); // ['P99']

The two directional differences give repairable information. “The groups differ” is true, but “P03 is missing and P99 is unexpected” tells the project author what to inspect. Do not silently delete P99 and present the remaining group as complete; the missing code still needs attention.

These are invented membership requirements, not a real attendance decision. In a live system, an unexpected code could reflect an input mistake, an outdated expected list or a genuinely different authorised group. The program reports the comparison; an appropriate person or rule decides what the discrepancy means.

Separate a subset check from complete equality

If every submitted code belongs to the expected group, the submitted group is a subset. That does not prove every expected participant is represented. P01 alone is a subset of the three-code expected group, yet it is not the complete group.

function isSubset(left, right) {
  for (const value of left) {
    if (!right.has(value)) return false;
  }
  return true;
}
console.log(isSubset(new Set(["P01"]), expectedGroup)); // true
console.log(sameMembers(new Set(["P01"]), expectedGroup)); // false

An empty Set is also a subset under this definition. If the task requires at least one submitted member, add that requirement explicitly rather than expecting membership logic to invent it. Mathematical correctness and an application's acceptance policy are related but separate.

Ask the learner to write three acceptance rules in ordinary language: no unexpected codes, at least one code, and exactly the expected group. Then identify which checks implement each rule. This is a useful transfer from collection operations to a real validation design.

Keep the representation change visible

The difference examples produce arrays, because spreading a Set creates an array before filter runs. That array is useful for displaying the discrepancy. It is not automatically a Set with membership methods. If another stage needs a Set, construct one deliberately.

Name the representations so another learner can follow them. missingCodes can be an array for display; missingCodeSet suggests a membership collection. Avoid a variable that changes from Set to array to text while keeping the same vague name.

When debugging, inspect the current structure as well as its visible values. Two structures can print similarly while supporting different operations. A child who understands that distinction can explain why a method is unavailable instead of repeatedly changing syntax until something runs.

CHAPTER 15 OF 15 · Save, test and practise

15. Keep the meaning beside the count

Back to contents

A good finished checker distinguishes event totals, distinct codes, overlap and directional differences. Its captions should tell the reader which number they are seeing. Four distinct codes in six messages is a clear statement; “four” alone is not.

For a Punggol practice session, use fictional codes, a small card sort and one changed condition. A parent can ask, “What does unique mean here?”, “What information did the Set leave out?” and “Is this display order part of the requirement?” Those questions reveal the child's reasoning without turning the evening into a vocabulary test.

Use the How Studying Works guide to plan a later retrieval task with different groups. Independent explanation of the changed membership question is the useful progress.

Technical references: MDN's Set overview, Set.add, Set.has, Set.delete and Set values. These rules support the invented examples without making claims about real pupils or their records.

Continue from here: Start Here · Tuition · Education · Pathways · Parenting 101 · All Site Routes

eduKate Punggol

Contact

83 Punggol Central, Singapore 828761

edu|Kate Bukit Timah

8 Fourth Avenue, Singapore 268674

By Appointment +65 8823 1234
admin@edukatesg.com

Email Us

When a child finally understands, school becomes less frightening and the future opens wider. Email us for the latest schedules and fees.

← 返回

感谢您的回复。 ✨

了解 eduKate Punggol 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读