The syntax of a Boolean object is very simple:
New Boolean (value)
Note: No initial value, or if you will set it to 0, -0, false, undefined, null or NaN. Then the default initial value will be ‘false’. In fact, if you will mention empty string (“”), still the initial value will not change from false.
The funny thing is if you will mention false in the string, then the initial value will be set to true.
Constructor – It will refer the function which made the object.
Prototype – It will let you add properties and methods to a Boolean object.
toSource () – This function will return a string that will represent the source code of the object.
toString () – It will return the string in result, depending on the Boolean object value.
valueOf () – This function will return the primitive value of an object.
We will take two examples to understand the tricky part.
We have set the initial value to false, and used function valueOf () to get the primitive value. Let’s see what happen, when you will run this program:
The output will be:
Yes, it is that simple. It has shown the initial value, that we have set to false. Now same example we will run in the second example, but it will show different answer. Tell me why?
In the below example, we have set the initial value to “false”. Remember, it is a string, and the second thing we did is, used valueOf () method.
The output you will see here is:
Now, can you tell me why we have got the true here? Instead, we have set the initial value to false. Yes, we have set the initial value to string and that is why it is showing true.
Tips to remember:
- toSource () is a non-standard function and may be it will not work in some browsers.