Skip to content

Commit 2f1add1

Browse files
BridgeARdanbev
authored andcommitted
util: improve Symbol.toStringTag handling
Only special handle `Symbol.toStringTag` if the property is not enumerable or not the own property of the inspected object. PR-URL: #27342 Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent 80c0b89 commit 2f1add1

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

lib/internal/util/inspect.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,8 +574,15 @@ function formatRaw(ctx, value, recurseTimes, typedArray) {
574574

575575
const constructor = getConstructorName(value, ctx);
576576
let tag = value[Symbol.toStringTag];
577-
if (typeof tag !== 'string')
577+
// Only list the tag in case it's non-enumerable / not an own property.
578+
// Otherwise we'd print this twice.
579+
if (typeof tag !== 'string' ||
580+
tag !== '' &&
581+
(ctx.showHidden ? hasOwnProperty : propertyIsEnumerable)(
582+
value, Symbol.toStringTag
583+
)) {
578584
tag = '';
585+
}
579586
let base = '';
580587
let formatter = getEmptyFormatArray;
581588
let braces;

test/parallel/test-util-inspect.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1267,8 +1267,20 @@ util.inspect(process);
12671267

12681268
{
12691269
// @@toStringTag
1270-
assert.strictEqual(util.inspect({ [Symbol.toStringTag]: 'a' }),
1271-
"Object [a] { [Symbol(Symbol.toStringTag)]: 'a' }");
1270+
const obj = { [Symbol.toStringTag]: 'a' };
1271+
assert.strictEqual(
1272+
util.inspect(obj),
1273+
"{ [Symbol(Symbol.toStringTag)]: 'a' }"
1274+
);
1275+
Object.defineProperty(obj, Symbol.toStringTag, {
1276+
value: 'a',
1277+
enumerable: false
1278+
});
1279+
assert.strictEqual(util.inspect(obj), 'Object [a] {}');
1280+
assert.strictEqual(
1281+
util.inspect(obj, { showHidden: true }),
1282+
"{ [Symbol(Symbol.toStringTag)]: 'a' }"
1283+
);
12721284

12731285
class Foo {
12741286
constructor() {

0 commit comments

Comments
 (0)