1

I'm trying to use console.log to see the properties of a Set object (like size). But if I try to log the keys in a Set, I get an empty array:

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

let keys = Object.keys(mySet);
console.log(keys); 

// Output: []

The same thing happens when I use a Map:

let myMap = new Map();
myMap.set('1', 1);
myMap.set('2', 2);
myMap.set('3', 3);

let keys = Object.keys(myMap);
console.log(keys); 

// Output: []
1
  • 2
    Which own enumerable properties does a Set have? Commented Nov 20, 2015 at 21:01

2 Answers 2

1

Why do you expect them to be available as keys? The Set and Map specs never promised it. The keys/values are available using the corresponding APIs.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

Sign up to request clarification or add additional context in comments.

Comments

0

{Map, Set}.prototype.keys() has another behavior both returns a new Iterator object not an array with keys:

from Map MDN reference:

Map.prototype.keys() Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

from Set MDN reference:

Set.prototype.keys() Is the same function as the values() function and returns a new Iterator object that contains the values for each element in the Set object in insertion order.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.