3 ms·
It's because the Symbol() function is creating a primitive value, not an object. There is no literal syntax for symbols, as there is for numbers, strings, etc.,
by thomasfoster96 11y ago
It's because the Symbol() function is creating a primitive value, not an object. There is no literal syntax for symbols, as there is for numbers, strings, etc., and so the symbol function is how you make them. Having a symbol constructor would be of little use (it'd be like using new Number()) and so it wasn't included.
- kevincennis 11y agoJust to expand on that a bit for anyone who might not know this: var s = new String('foo'); typeof s; // 'object' That is, when you use the `new` keyword, you get back an object instead of a primitive. Since symbols are always primitives, disallowing the `new` keyword actually prevents inconsistency with the rest of the language in the sense that it doesn't allow you to create non-objects with a constructor.
- draw_down 11y agoStrings are always primitives too, but you can call `new String` and receive an object, not an error. This is just straight-up inconsistent, I don't see the point of arguing otherwise.
- thomasfoster96 11y agoTake a look at this[0] with regards to strings. I'm not really sure why you'd use new String anyway - it won't always act as a string primitive. Rather than making Symbol reimplement the same quirks that other built in constructors do, isn't not allowing a Symbol constructor going to avoid a lot of confusion? For example, if you created an object using a hypothetical symbol constructor, the symbol would be converted to a string if you tried to use it as an object key (internally, JavaScript sees your symbol object as an object, not a symbol), which is simply creating problems for a naive programmer. [0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString#Distinction_between_string_primitives_and_String_objects https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- draw_down 11y agoThe point under debate is whether it's inconsistent with Number, String, and Boolean, which it is. I agree `new String` is not particularly useful.
- thomasfoster96 11y agoSorry, I think I misunderstood your point. I thought you meant that inconsistency was worse than misusing constructors.
- nailer 11y agoOk so it's unique in that unlike Number, String, Boolean it has an primitive version but no object version. That could still make it not error when called the same was as other constructors.
- thomasfoster96 11y ago> That could still make it not error when called the same was as other constructors. What do you mean? That new Symbol() should just ignore the 'new'?
- nailer 11y ago'Was' = 'way'. Typo, sorry.