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 following code
var bool = new Boolean(false);
if (bool){
alert(bool);
}
it will alert
but you will get false
, which is kinda confusing (false
!= falsy).
so is there ever a point in using primitive data-types and especially primitive booleans?
The primitive values are very useful (ex of primitive values: true, false, null, 1, 2, etc). What you are talking about in the question are the Object wrappers around them.
Object wrappers are useful because it allows you to add functions to be called on them. One more important thing is that when you call methods on the primitive values, Object wrappers are created over them and the methods are called on the Object wrappers*.
Example 1: String
String.prototype.sayHello = function() {
return this + ' says hello';
};
// calling a method on a string literal temporarily converts it to a String
console.log('John'.sayHello()); // 'John says hello'
Example 2: Boolean
var bool = new Boolean(false);
console.log(bool); // Boolean
console.log(bool.toString()); // 'false'
console.log(bool.valueOf()); // false
// How you can use it:
Boolean.prototype.toCaps = function() {
return this.valueOf().toString().toUpperCase();
};
console.log(bool.toCaps()); // 'FALSE'
// calling a method on a boolean literal temporarily converts it to a Boolean
console.log(true.toCaps()); // 'TRUE'
console.log((1 === 1).toCaps()); // 'TRUE'
DEMO: http://jsbin.com/apeGOve/1/edit
*) Different Object wrappers are created each time a method is called on a primitive value:
String.prototype.getWrapper = function() { return this; };
String.prototype.setTest = function() { this.test = 'test' };
String.prototype.getTest = function() { return this.test; };
var str = '123';
console.log('Different wrappers each time',str.getWrapper() === str.getWrapper());
var wrapper = str.getWrapper();
wrapper.setTest();
console.log(wrapper.getTest());
console.log(str.getTest());