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."
)
Boolean Algebra Truth Tables For A 2-input AND Gate For a 2-input AND gate, the output Q is true if BOTH input A “AND” input B are both true, giving the Boolean Expression of: ( Q = A and B ). Note that the Boolean Expression for a two input AND gate can be written as: A.B or just simply AB without the decimal point.
A Boolean expression is any expression that has a Boolean value. For example, the comparisons 3 < 5, x < 5, x < y and Age < 16 are Boolean expressions. The comparison 3 < 5 will always give the result true, because 3 is always less than 5.
The three basic boolean operators are: AND, OR, and NOT.
A boolean expression is an expression that evaluates to a boolean value. The equality operator, == , compares two values and produces a boolean value related to whether the two values are equal to one another.
this.swung
not a local variable, but a property of Ninja
's instances. So, the property can be modified by an external method.
To make sure that swingSword
always return a boolean, an explicit conversion using !!
is useful.
As for your code: I believe that it should be !this.swung
, because !!this.swung
returns false
for this.swung = false
:
this.swung = false; // Defined in code
!!this.swung === !!false; // See previous line
!!false === !true; // Boolean logic
!true === false; // Boolean logic
false === this.swung; // See first line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With