a pretty simple question, is there ever a case where using a primitive data-type is preferable in javascript, i am specifically bothered by primitive booleans, consider the foll
Your example:
var bool = new Boolean(false);
if (bool){
alert(bool);
}
and you're wanting to know why it alerts false.
bool
is the variable, you assigned it a value when you created it. So, when you say if(bool)
JavaScript does some coercion and tests whether bool
is falsy, it isn't, so the conditional block executes. Now you're at alert(bool)
which will try to call the toString method of your object and display the result. The toString method of the boolean object returns the value of the boolean object as a string so, you get the word "false" alerted.
Go ahead, try
var bool = new Boolean(false);
bool.toString = function () {
return 'I need a banana';
}
if (bool){
alert(bool);
}
and you'll get completely different results.
This brings us to your other question of "why" you'd even use the boolean constructor: you can assign properties to the boolean object, you can not assign properties to true
and false
. You may want to inherit from the boolean object when building some logic handling library with chainable methods, for instance.