Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Why is Set object split string?
const set = new Set("123");

console.log(set);

Output is "Set { '1', '2', '3' }"

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Because strings are iterable, and when you give the Set constructor an iterable object,¹ it loops through the values provided by the object's iterator and adds them to the set. In the case of strings, the string iterator iterates the strings code points — in your example, "1", "2", and "3". (For more about "code points" vs. "code units" and what a string is, read my blog post.)

If you want to add a string to a set, you have to do add separately or wrap it in another iterable (like an array):

// Add separately:
let set = new Set();
set.add("123");
console.log(set.size); // 1
console.log([...set]); // ["123"]

// Or wrap:
set = new Set(["123"]);
console.log(set.size); // 1
console.log([...set]); // ["123"]


¹ (or a primitive such as a string that coerces to an iterable object)

about 4 years ago · Juan Pablo Isaza Report

0

The Set constructor takes an iterable and takes every value of it.

Strings have an @@iterator property by default which makes them iterable:

const foo = "xyz";

console.log(...foo);

const [a, b, c] = foo;
console.log(a, b, c);

for (const char of foo)
  console.log(char);

Therefore, this is exactly what happens when you pass a string to a Set constructor - it draws every value just as it would with any other iterable:

const foo = "xyz";
const bar = [1, 2, 3]

console.log("set of string:", new Set(foo));
console.log("set of array :", new Set(bar));
<h1>Check the browser console</h1>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!