!! expression for boolean

I read John Resig Ninja JavaScript Secrets and saw this code:

function Ninja(){ this.swung = false; // Should return true this.swingSword = function(){ return !!this.swung; }; } 

I know that !! used to convert an expression to boolean. But my question is why it uses:

 return !!this.swung; 

Isn't that redundant because swung already a boolean variable or am I missing something?

By the way, here is the complete 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." ) 
+4
source share
1 answer

this.swung not a local variable, but a property of Ninja instances. Thus, the property can be changed by an external method.

To make sure swingSword always returns a boolean, it is useful to use an explicit conversion using !! .

As for your code: I believe 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 
+5
source

Source: https://habr.com/ru/post/1397622/


All Articles