0

I am learning to use Sets in JavaScript and noticed some odd behavior when going through the documentation.

let beverageSet = new Set();
beverageSet.add('Rum');
beverageSet.add('Tea');
beverageSet.add('OJ');
console.log(beverageSet); // returns Set [‘Rum’, ‘OJ’]
beverageSet.delete('Tea');
console.log(beverageSet); // returns Set [‘Rum’, ‘OJ’]

I know that hoisting pulls all variables to the top of the scope before executing code, but I have not seen anything showing that it would affect console.log()/methods called on arrays and Sets.

Is this an effect of hoisting or something else? How can I get around this and console.log() the full Set before deleting an item and then console.log() again?

wesree
  • 57
  • 9
  • 2
    I think you're seeing `console.log()` behavior that's confusing things. Are you using Chrome? – Pointy Jan 04 '17 at 21:16
  • 1
    the first call of `console.log(beverageSet);` gives `Set {"Rum", "Tea", "OJ"}` to me – RomanPerekhrest Jan 04 '17 at 21:19
  • Yes I am using Chrome @Pointy, should I investigate console.log() behavior in Chrome to get to the bottom of this? I do get the same outcome in Firefox as well. – wesree Jan 04 '17 at 21:22
  • I also get the same behavior when using an array instead of a set. – wesree Jan 04 '17 at 21:27

1 Answers1

2

The console.log implementation sometimes decides to get the value asynchronously, thereby showing results that might have mutations applied to them, that really occurred after the console.log statement.

To avoid this, take a copy in one or the other way, for instance like this:

console.log([...beverageSet]); // convert set to new array.

See also Bergi's answer to a question concerning the asynchronicity of console.log.

There is also a chromium issue on this: 50316 - Console.log gives incorrect output in Chrome Developer Tools console. It might be an interesting read.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286