使用Symbol()函数为对象添加匿名属性的相关疑问
Great question! Let’s unpack this confusion step by step—there are two key pieces of JavaScript behavior at play here.
First: Why does your Symbol property show enumerable: true in its descriptor?
By default, when you assign a Symbol as an object property directly (like obj[Symbol()] = 'myValue'), that property is not enumerable—which lines up with what MDN states. If you’re seeing enumerable: true, you almost certainly explicitly set it that way using Object.defineProperty() or Object.defineProperties(), like this:
const mySym = Symbol(); const myObj = {}; // Manually defining the property with enumerable: true Object.defineProperty(myObj, mySym, { value: 'test', enumerable: true }); console.log(Object.getOwnPropertyDescriptor(myObj, mySym).enumerable); // Logs true
Second: Why can’t for..in find the Symbol property, even if it’s enumerable?
This is a core design choice of the for..in loop: it only iterates over enumerable string-based keys (both own and inherited from the prototype chain). Symbol keys—regardless of whether their enumerable flag is true or false—are never included in for..in iterations.
If you need to work with Symbol properties, use methods built specifically for them:
Object.getOwnPropertySymbols(obj): Returns all own Symbol keys of an objectReflect.ownKeys(obj): Returns all own keys of an object (both string and Symbol types)
Here’s a quick demo to see this in action:
const sym1 = Symbol('first'); const sym2 = Symbol('second'); const demoObj = { [sym1]: 'value1', regularKey: 'value2' }; // Manually add an enumerable Symbol property Object.defineProperty(demoObj, sym2, { value: 'value3', enumerable: true }); // for..in only picks up the string key for (const key in demoObj) { console.log(key); // Logs "regularKey" } // Get all own Symbol keys console.log(Object.getOwnPropertySymbols(demoObj)); // Logs [Symbol(first), Symbol(second)] // Get all own keys (strings + Symbols) console.log(Reflect.ownKeys(demoObj)); // Logs ["regularKey", Symbol(first), Symbol(second)]
A quick note on MDN’s wording
MDN says that Symbol-backed properties are "anonymous and should be non-enumerable"—this refers to the default behavior, not a hard rule. You can set them to enumerable if you want, but that won’t make them visible to for..in because the loop doesn’t consider Symbol keys at all.
内容的提问来源于stack exchange,提问作者Animesh Kumar

