3 ms·
Symbols are odd. Maybe it's just me but they feel like they work "funny" in JavaScript. As the article says you can't implicitly convert a symbol's description
by BinaryIdiot 11y ago
Symbols are odd. Maybe it's just me but they feel like they work "funny" in JavaScript.
As the article says you can't implicitly convert a symbol's description to string. Symbol is now the only native object in JavaScript that has this behavior.
var str = "something" + "str"; // Works
var num = "something" + 5; // Works
var func = "something" + function () { }; // Works
var obj = "something" + { some: "test" }; // Works
var bool = "something" + true; // Works
var dt = "something" + Date.now(); // Works
var und = "something" + undefined; // Works
var nul = "something" + null; // Works
var nan = "something" + NaN; // Works
var sym = "something" + Symbol("test"); // Throws TypeError
Another thing, which is more of a style thing in my opinion, is you can actually define a property with a Symbol which just seems awkward to me. I mean sure you can use it as a property by design so why wouldn't you be able to use defineProperty? I always felt those should be public types of properties where you can add additional logic where necessary.
var obj = { };
Object.defineProperty(obj, Symbol("MyProp"), {
get: function () { return 15; }
});
I feel like almost the same thing with Symbol could be accomplished with a simple UUID generator. It's a neat little thing it just feels awkward to me with how JavaScript works.
- jkrems 11y agoThe other funny thing is: ES6 introduced `Map`, `Set`, and the `class` keyword. All of them throw if you try to create a new instance without `new`. It also introduced `Symbol`, which throws if you do use `new`.