Javascript has lot's of "tricks" around types and type conversions so I'm wondering if these 2 methods are the same or if there is some corner case that makes them different?
Javascript has lot's of "tricks" around types and type conversions so I'm wondering if these 2 methods are the same or if there is some corner case that makes them different?
String() [the constructor call] is basically calling the .toString()
.toString() and String() can be called on primitive values(number,boolean,string) and basically will do nothing special:
true => 'true'
false => 'false'
17 => '17'
'hello' => 'hello'
But calling these functions on objects is where things gets interesting:
if the object has it's own .toString() function it will be called when ever you need this object to be treated as a string(explicitly/implicitly)
let obj = {
myName:"some object",
toString:function(){ return this.myName; }
}
//implicitly treating this obj as a string
"hello " + obj; //"hello some object"
//OR (explicitly)
"hello " + String(obj) //calling the existent toString function
//OR
"hello " + obj.toString(); //calling toString directly
By the way if you want to treat this object as a number it should has a .valueOf() function defined in it.
what if we have both in one object?
if we want to treat this object as a string => use .toString()
if we want to treat this object as a number => use .valueOf()
what if we only have .valueOf() defined?
.valueOf() defined inside the object will be called whether we want to handle the object as a string or as a number
I just tried this with ES6 and found out that for String() to look at valueOf() inside of the object, the object has to have toString() method. If the object does not have toString() then console returns '[object Object]' regardless of having valueOf() or not. So in the the first "step", we always have to have toString() regardless, else String() method wouldn't look at valueOf.
Please check this:
let obj = {
name:'b',
age:22,
valueOf: function(){
return 'heeee';
}
}
String(obj); // prints '[object Object]'
On the other hand,
let obj = {
name:'b',
age:22,
toString:null,
valueOf: function(){
return 'heeee';
}
}
String(obj); // prints 'heeee'
let obj = {
name: 'b',
age: 22,
valueOf: function() {
return 'heeee';
}
}
console.log(String(obj));
let obj2 = {
name: 'b',
age: 22,
toString: null,
valueOf: function() {
return 'heeee';
}
}
console.log(String(obj2));