Why Symbols not convert string implicitly - javascript

Why Symbol('test').toString() works well, but I can't use '' + Symbol('test')?
It will throw Error:
cannot convert a Symbol value to a string
Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()?

According to ECMA-262, using the addition operator on a value of type Symbol in combination with a string value first calls the internal ToPrimitive, which returns the symbol. It then calls the internal ToString which, for Symbols, will throw a TypeError exception.
So calling the internal ToString is not the same as calling Symbol.prototype.toString.
So I guess the answer to:
Why does the implicit type conversion not work?
is "because the spec says so".

You can, however you're not meant to do so by accident.
console.log(''+String(Symbol('My symbol!')))
// Symbol(My other symbol!)
console.log(Symbol('My symbol!').description)
// My other symbol!
console.log(Symbol.keyFor(Symbol.for('My other symbol!')))
// My other symbol!
Note: Symbol.keyFor only works for symbols created via the Symbol.for function.
Symbol.keyFor(Symbol('My symbol!')) will evaluate to undefined.
You can also use .description to get the string value used to create the symbol.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/keyFor

your type not string
'' + Symbol('test').toString()
you can check, Symbol is a new type in ES6
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol
The Symbol() function returns a value of type symbol, .....

Related

Confusion related to Symbol.toprimitive method in js

In javascript, there is a symbolic property known as Symbol.toprimitive, which have function value, am I right?
If so, then in this method, the first word (ie. Symbol) is an system symbol?
And when we call this method, is there a formation of temporary object as we are creating property for a value that is primitive (symbol), of which value is an method?
And third confusion is in this method (ie. [Symbol.toprimitive] (hint), how the parameter hint knowns that hint should be "string" or "number" or "default" , I mean I know the rules but from where this parameter gets its value?
Thanks for your valuable answer :)
...there is a symbolic property known as Symbol.toprimitive, which have function value, am I right?
No, Symbol.toPrimitive is a Symbol, not a function. It's used as the key of an object property whose value should be a function, but it's a Symbol.
...then in this method, the first word (ie. Symbol) is an system symbol?
It's the Symbol global object, which is a container for "well-known symbols" used for various purposes in JavaScript code.
And when we call this method, is there a formation of temporary object as we are creating property for a value that is primitive (symbol), of which value is an method?
Symbol.toPrimitive is not a method, so the question doesn't come up.
And third confusion is in this method (ie. [Symbol.toprimitive] (hint), how the parameter hint knowns that hint should be "string" or "number" or "default" , I mean I know the rules but from where this parameter gets its value?
The value of the hint is built into the places in the JavaScript specification that call the function. For example, the unary - operator uses ToNumeric on its operand, which uses ToPrimitive, passing in the "hint" that it wants a number. ToPrimitive is what passes the "number" hint to the [Symbol.toPrimitive] (aka ##toPrimitive) method of the object.
Let's consider a simple example, which should help you understand things a bit more:
// An object with its own Symbol.toPrimitive property
// referring to a function that implements the behavior
// we want for this object
const obj = {
[Symbol.toPrimitive](hint) {
console.log(`The hint is ${hint}`);
return hint === "number" ? 42 : "forty-two";
}
};
// `-` uses ToNumeric which uses ToPrimitive asking for a
// number if possible
let x = 4 - obj;
console.log(`x = ${x}`);
// In contrast, string concatenation doesn't have a preference
let y = "" + obj;
console.log(`y = ${y}`);
// But the String function, which always wants to get a
// string if it can, asks for a string
let z = String(obj);
console.log(`z = ${z}`);

Is there difference between creating a wrapped BigInt or Symbol with the "new" keyword in JavaScript?

I have examined the wrapped symbol objects using the following code.
const symObj = Object(sym);
const symObjNew = new Object(sym);
// I can see no difference between symObj and symObjNew
console.log(`typeof symObj === 'object' is ${typeof symObj === 'object'}`); // true
console.log(`typeof symObjNew === 'object' is ${typeof symObjNew === 'object'}`); // true
I have also examined the symObj and symObjNew in devtools using node --inspect-brk. I don't see any difference between them. The same is true of BigInt.
TL;DR
There is no difference between new Object(realthing) and Object(realthing). They do the same thing.
Much longer answer
When it comes to JS, reading the spec is always a good idea, although it can be incredibly hard to figure out what things mean. So, let's dive into this: in this case, we want the rules for how Object() works:
19.1.1The Object Constructor
The Object constructor:
is the intrinsic object %Object%.
is the initial value of the Object property of the global object.
creates a new ordinary object when called as a constructor.
performs a type conversion when called as a function rather than as a constructor.
is designed to be subclassable. It may be used as the value of an extends clause of a class definition.
So we have two cases to look at: Object(sym), and new Object(sym).
What happens for Object(sym)?
19.1.1.1 Object([ value ])
When the Object function is called with optional argument value, the following steps are taken:
If NewTarget is neither undefined nor the active function, then
Return ? OrdinaryCreateFromConstructor(NewTarget, "%ObjectPrototype%").
If value is null, undefined or not supplied, return ObjectCreate(%ObjectPrototype%).
Return ! ToObject(value).
(Note that ? and ! here are not "code", they are spec syntax. ! means "this operation will always return a normal value whereas ? may return an abnormal value)
In this case, we didn't use new, so step 1 doesn't apply. The value is not nullish, so step 2 doesn't apply, and we end up executing step 3: we perform a type conversion so we end up with a new object for which typeof will now say "object", no matter what it was before, but with the original data preserved as value.
What happens for new Object(sym)?
Looking at 19.1.1.1 again, we're using new this time, so we might expect step 1 to kick in: after all, there is a NewTarget (by definition: we used new so there is a NewTarget), but it turns out the NewTarget is the Object function itself, making NewTarget the active function, and so step 1a does not kick in.
We also have a value, and it's not nullish, so step 2 doesn't kick in, and we again run step 3: type conversion.
So Object(sym) and new Object(sym) do exactly the same thing, just for subtly different reasons.
So how does ToObject work?
Looking at the spec again:
7.1.13ToObject ( argument )
The abstract operation ToObject converts argument to a value of type Object according to Table 12:
Undefined Throw a TypeError exception.
Null Throw a TypeError exception.
Boolean Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 19.3 for a description of Boolean objects.
Number Return a new Number object whose [[NumberData]] internal slot is set to argument. See 20.1 for a description of Number objects.
String Return a new String object whose [[StringData]] internal slot is set to argument. See 21.1 for a description of String objects.
Symbol Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 19.4 for a description of Symbol objects.
Object Return argument.
So the first observation should be that "if it's an object, ToObject does nothing". That's of course not the case for your Object(sym), so what happens for it?
A new object gets built, with its type set to object (irrespective of what the input value type is), and this new object's prototype will be set to match whatever the input value's prototype was. Then the new object's internal value literally gets copied over from the input value that's getting converted.
But we're not quite done
typeof is useless for testing "what a thing is".
Remember that almost everything in JS is an object, and typeof will only tells you the basic type of something. As such, there are only six answers it can give you:
object
function
string
symbol
number
undefined
That's it. The typeof operator tells you nothing about the what the most specific type is, instead it tells you what the most generic type is.
For the specific type, either use thing.constructor.name to find out which constructor function actually got used to build the thing you're examining, or use thing.__proto__ to get a reference to that type. Or, if you have the type already and merely need to test to see if "thing is a ...", use the instanceof operator:
> typeof 3
"number"
> typeof Object(3)
"object"
> Object(3).constructor.name
"Number"
> Object(3).__proto__
Number { 0 }
> Object(3) instanceof Number
true
As specified in MDN:
When called in a non-constructor context, Object behaves identically to new Object().
I'd venture to guess this is another one of JavaScript's infamous backwards compatibility 'features', back during such a time that the new keyword didn't exist.
You can also check the ECMAScript spec for details:
When the Object function is called with optional argument value, the
following steps are taken:
If NewTarget is neither undefined nor the active function, then
Return ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").
If value is undefined or null, return OrdinaryObjectCreate(%Object.prototype%).
Return ! ToObject(value).
As thoroughly explained by Mike's answer, both cases in your sample snippet end up in Step 3, which performs type conversion on the argument. So there is no difference whatsoever.

Why does this evaluate as false?

Why does comparing an explicitly called String constructor to an implicit string evaluate true, but adding the new keyword makes it evaluate false on deep equals, but true again on shallow equals?
> "hello"===String("hello")
true
> "hello"==new String("hello")
true
> "hello"===new String("hello")
false
Edit: after further testing, this appears to happen with all types that have implicit constructors.
Edit 2: to clarify, this is not a question of == vs. ===, but one of implicit vs. explicit constructors.
When you use the new keyword you are creating an object. If you were to check the typeof new String('hello') you will see that it is of type object. Checking the type of 'hello' on its own will yield string.
As you may know, using a strict equals operator (===) will check for both value and type, so it will return false due to the types not matching.
The reason the expression without the new keyword returns true is because calling upon the String global object is not the same as calling the constructor using new:
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
As such, the type of the return value will be string and not object, so the strict check will return true.
The difference between == and === is that === requires the type to be the same, while == does not.
So this is telling you that both "hello" and String("hello") are of the same type (which is string); but new String("hello"), while it has the same value, is a different type (which is object)

JavaScript loose comparison between an object and a string

The below code,
var someObject = {"attr":1}; // line:1
alert(someObject == "someString"); //line:2
fails with the exception: unexpected call to method or property access in line 2.
When i change the comparison to a strict equals to, it works fine.
alert(someObject === "someString");
I understand that a doing a strict comparison does not do a type conversion, but am unable to determine at what point exactly is this error thrown when the type conversion happens.
Note: The exact object has around ten attributes and each attribute has a string value of significant length.
Minimal input with which i am able to reproduce this error:
someObject = {
"a":"RESOLVED",
"b":"A-1444779652190",
"c":"{s=Hello, id=A-1444779652190}"
}
(c is a string, don't think it really matters here)
When you do someObject == "someString", the Abstract Equality Comparison Algorithm does this:
If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) ==
y.
When ToPrimitive is called with an object,
Return a default value for the Object. The default value of an object
is retrieved by calling the [[DefaultValue]] internal method of the
object, passing the optional hint PreferredType. The behaviour of
the [[DefaultValue]] internal method is defined by this specification
for all native ECMAScript objects in 8.12.8.
Summarizing, When [[DefaultValue]] is called on a non-Date native object with no hint, it does this:
If the object has a toString method which returns a primitive, the default value is that primitive
If the object has a valueOf method which returns a primitive, the default value is that primitive
Throw TypeError
My guess is that some code modified Object.prototype.toString or Object.prototype.valueOf, and now they may throw when called by ToPrimitive.

Safe way to get a string representation of any JavaScript value or object

I want to get a string represention of any object or value in JavaScript. I did a couple of experiments.
> var a = document.createTextNode('foo'); a
"foo"
> var a = document.createTextNode('foo'); a.toString()
"[object Text]"
> var a = 1; a.toString()
"1"
> (1).toString()
"1"
> 1.toString()
SyntaxError: Unexpected token ILLEGAL
I have the following questions:
Why does 1.toString() fail?
Will the following function return me a string representation of every possible JavaScript object, value or literal? Function: function str(a) {return a.toString()}
Is there any other alternative to the function str I have written in the previous point?
1). Why does 1.toString() fail?
The JavaScript parser only uses a 1 character lookahead and can't determine if that's 1.0 or 1.toString(). You can use 1..toString() to get around that.
2). Will the following function return me a string representation of every possible JavaScript object, value or literal? Function: function str(a) {return a.toString()}
Any literal will be converted to a temporary object in order to have its toString() called. If the object has its own toString() defined, it will be called. Otherwise, it will use Object.prototype.toString() (having gone up the prototype chain) for almost all cases (the other case is an object with a null prototype).
3). Is there any other alternative to the function str I have written in the previous point?
Yes. You can invoke the toString() implicitly by concatenating an empty string, e.g. 1 + "". You can also use the String constructor, e.g. String(value) (thanks T.J. Crowder). The advantages of these other ones is no exception will be thrown if you attempt to call toString() on null or undefined.
However, these tricks will convert null and undefined to their string equivalents (almost never what you want). One dirty trick is to put the value in a literal array, e.g. [value] and then call toString() on it. This will actually invoke join(","), but seeing as it only has one member, the comma will never become part of the string.
The real power of doing this is that null and undefined will just become an empty string. If that's OK for your program, then it can be useful. Keep in mind to comment this solution as it's not immediately obvious what this code is doing. Alternatively, check value == null which will detect null and undefined and handle it appropriately.
However, if you're wanting a string in order to classify a value, you can get the type's [[Class]] like so...
var getInternalClass = function(value) {
return Object.prototype.toString.call(value).slice(8, -1);
};
This will invoke the Object's toString() and set the ThisBinding to the value provided as the argument. This is the only way to expose an object's internal [[Class]]. The advantage of this (over typeof, for example) is that primitives and objects will always return the same value (with the primitives being converted to temporary objects, boxed by the call() context in non-strict mode).
for 1.toString(), you need to do:
1 .toString() //add space before dot (.) to avoid taking it as decimal
shortest way (alternative to function str ) to convert to string is:
var str = str + '';
Your str(a) function is correct but it will call the default implementation of toString() inherited from Object. So yes, your function will give you string representation of every JS object but not in way you want it. You need to override it.
var o = new Object();
o.toString(); // returns [object Object]
See here for reference and overriding: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Categories