I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
Share Improve this question edited Apr 19, 2015 at 10:52 niton 9,20923 gold badges35 silver badges56 bronze badges asked Jun 27, 2011 at 22:14 BlahBlah 391 bronze badge 2-
1
It's called a shorthand, not an esoteric JS nuance. In the same way that the
+
operator is used to convert to a number (e.g.:+"0"
) and that+""
is used to convert to a string. – HoLyVieR Commented Jun 27, 2011 at 23:25 - 1 possible duplicate of What is the !! operator in JavaScript? – Crescent Fresh Commented Jun 28, 2011 at 1:15
4 Answers
Reset to default 12It is just an obtuse way to cast the result to a boolean.
Yes, it's NOT-NOT. It is monly used idiom to convert a value to a boolean of equivalent truthiness.
JavaScript understands 0.0
, ''
, null
, undefined
and false
as falsy, and any other value (including, obviously, true
) as truthy. This idiom converts all the former ones into boolean false
, and all the latter ones into boolean true
.
In this particular case,
a && b
will return b
if both a
and b
are truthy;
!!(a && b)
will return true
if both a
and b
are truthy.
The && operator returns either false or the last value in the expression:
("a" && "b") == "b"
The || operator returns the first value that evaluates to true
("a" || "b") == "a"
The ! operator returns a boolean
!"a" == false
So if you want to convert a variable to a boolean you can use !!
var myVar = "a"
!!myVar == true
myVar = undefined
!!myVar == false
etc.
It is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.
It will convert anything to true or false...