Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!!expression for boolean

Tags:

javascript

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."
)
like image 984
Dev555 Avatar asked Feb 21 '12 14:02

Dev555


People also ask

How do you write a Boolean expression?

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.

What is a Boolean expression example?

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.

What are the 3 Boolean expressions?

The three basic boolean operators are: AND, OR, and NOT.

Is == a Boolean expression?

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.


1 Answers

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
like image 174
Rob W Avatar answered Oct 25 '22 04:10

Rob W