I was reading John Resig’s Secrets of JavaScript Ninja and saw this code:
function Ninja(){
this.swung = false;
// Should return true
this.swingSword = function(){
return !!this.swung;
};
}
I know !! is used to convert an expression into boolean. But my question is why does he use:
return !!this.swung;
Isn’t that redundant because swung is already a boolean variable or am I missing something ?
BTW here is full relevant code just in case:
function Ninja(){
this.swung = false;
// Should return true
this.swingSword = function(){
return !!this.swung;
};
}
// Should return false, but will be overridden
Ninja.prototype.swingSword = function(){
return this.swung;
};
var ninja = new Ninja();
assert( ninja.swingSword(), "Calling the instance method, not the prototype method."
)
this.swungnot a local variable, but a property ofNinja‘s instances. So, the property can be modified by an external method.To make sure that
swingSwordalways return a boolean, an explicit conversion using!!is useful.As for your code: I believe that it should be
!this.swung, because!!this.swungreturnsfalseforthis.swung = false: