0

Are symbols acting like objects in JavaScript or a Symbol object is being created under the hood in the following example:

const symbol = Symbol();

Symbol.prototype.sayHello = function () {
  console.log("sayHello");
};

symbol.sayHello(); //"sayHello"

I know that in JavaScript the function Symbol cannot be invoked with the keyword "new". But can it be done behind the scenes? I already know that when we use methods on primitive values like this:

console.log("333".startsWith("33")); //true

A String object is being created and the method String.prototype.startsWith is being invoked. After that, the object is being garbage-collected. But is it the same case when we work with symbols? Even though we cannot explicitly invoke the function Symbol as a constructor function?

Petar
  • 23
  • 1
  • 7
  • Yes, it’s exactly the same with symbols; they’re primitive types, and you can still do `Object(Symbol())`. – Sebastian Simon Jan 08 '23 at 02:08
  • 3
    `new Symbol` is disallowed for other reasons. You can try searching for some very old TC39 proposal texts (keywords “tc39 harmony wiki strawman”). For example: [the 2013-09 meeting notes](//archives.ecma-international.org/2013/notes/2013-09/sept-18.html#44-symbols): _“DD: `new Symbol()` is a probable footgun; should it do anything at all? Maybe just throw? Because we don't have symbol literals, so unlike `new Number(5)` vs. `Number(5)` vs. `5`, the choice is not obvious; people will try to do `new Symbol()` not realizing that this creates a wrapper.”_ – Sebastian Simon Jan 08 '23 at 02:19

1 Answers1

2

Yes, symbols are primitive values, and invoking methods on them works just like for strings or numbers - a wrapper object gets implicitly created that inherits from Symbol.prototype.

You cannot create such a wrapper object using new Symbol, but you still can create it by calling

const symbol = Symbol();
const wrapper = Object(symbol);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375