In JavaScript, the operation of converting an object to a boolean is very simple: all objects are true after being converted to a boolean; even objects such as new Boolean(false) are still true after being converted to a boolean.
The code copy is as follows:
var x = new Boolean(false);
if(x){
console.log("x is true");
}
When converting an object to string or number, JavaScript will call two conversion functions of the object: toString() and valueOf().
toString()
The function of the toString() function is to return the string representation of the object. The default toString() method of object in JavaScript returns the string "[object Object]". A new toString() method can be implemented when defining a class, thus returning more readable results. JavaScript defines a more readable toString() method for array objects, function objects, regular expression objects, and Date date objects:
1.array's toString() method will return comma-separated array members. For example, [1,2,3].toString() will return the string "1,2,3".
2. The toString() method of function will return the text definition of the function. For example, (function(x){return x*2;}).toString() will return the string "function(x){return x*2;}".
3.RegExp's toString() method is similar to function's toString() method, which will return the text definition of the regular expression. For example, //d+/g.toString() will return the string "///d+/g".
4.Date's toString() method will return a readable date and time string.
valueOf()
The function of the valueOf() function is to return the numerical representation of the object. The default valueOf() method of object in JavaScript will return the object itself. Like toString(), a new valueOf() method can be implemented when defining a class, thus returning the required result. JavaScript defines a more readable valueOf() method for Date objects:
1.Date's valueOf() method will return a value, which is the time difference (in milliseconds) between the Date object and zero hours on January 1, 1970.