JavaScript Introducing ES2015 Objects and New Collection Types Set

Brendan Whiting
MOD
Brendan Whiting
Front End Web Development Treehouse Moderator 83,954 Points

Set() seems to not change at all when transpiled to old JavaScript

I ran this code through the babel online transpiler. It changed the let keywords to var but it didn't change Set() at all. Why is that? How long has Set() been around?

https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Ces2015-loose%2Ces2016%2Ces2017%2Clatest%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&code='use%20strict'%3B%0A%0Alet%20classroom%20%3D%20new%20Set()%3B%0A%0Alet%20stevenJ%20%3D%20%7B%20name%3A%20%22Steven%22%2C%20age%3A%2022%20%7D%2C%0A%20%20%20%20sarah%20%3D%20%7B%20name%3A%20%22Sarah%22%2C%20age%3A%2023%20%7D%2C%0A%20%20%20%20stevenS%20%3D%20%7B%20name%3A%20%22Steven%22%2C%20age%3A%2022%20%7D%0A%0Aclassroom.add(stevenJ)%3B%0Aclassroom.add(sarah)%3B%0Aclassroom.add(stevenS)%3B%0Aclassroom.add(sarah)%3B%0A%0Aif%20(classroom.has(stevenJ))%20console.log('stevenJ%20is%20in%20the%20classrom')%3B%0Aif%20(classroom.has(sarah))%20console.log('sarah%20is%20in%20the%20classrom')%3B%0Aif%20(classroom.has(stevenS))%20console.log('stevenS%20is%20in%20the%20classrom')%3B%0A%0Aconsole.log('classroom%20size%3A'%2C%20classroom.size)%3B%0Aclassroom.delete(stevenJ)%3B%0Aconsole.log('classroom%20size%3A'%2C%20classroom.size)%3B%0A%0A%2F%2F%20Create%20an%20array%20of%20students%20from%20the%20classroom%20set%0A%0Alet%20arrayOfStudents%20%3D%20Array.from(classroom)%3B%0Aconsole.log(arrayOfStudents)%3B%0A%0A%2F%2F%20Create%20a%20set%20from%20an%20existing%20array%0Alet%20alumni%20%3D%20new%20Set(arrayOfStudents)%3B%0Aconsole.log('alumni%20size%3A'%2C%20alumni.size)%3B

2 Answers

Ken Howard
STAFF
Ken Howard
Treehouse Guest Teacher

The feature has been implemented in most browsers for a while but it is new to the ECMA specification.

Specification: http://www.ecma-international.org/ecma-262/6.0/#sec-set-constructor

Here's the browser compatibility list: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#Browser_compatibility

This is because Babel only changes new syntax like destructuring or let and not new library functionality. Older browsers understand the line var classroom = new Set(); just fine, provided that a Set constructor exists. To make this constructor available, you need to include a polyfill.