Possible Duplicate:
What is the !! (not not) operator in JavaScript?
I have encountered this piece of code:
function printStackTrace(options) {
options = options || {guess: true};
var ex = options.e || null, guess = !!options.guess;
var p = new printStackTrace.implementation(), result = p.run(ex);
return (guess) ? p.guessAnonymousFunctions(result) : result;
}
And I couldn’t help to wonder why the double negation? And is there an alternative way to achieve the same effect?
(The code is from https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js.)
It casts to boolean. The first
!negates it once, converting values like so:undefinedtotruenulltotrue+0totrue-0totrue''totrueNaNtotruefalsetotruefalseThen the other
!negates it again. A concise cast to boolean, exactly equivalent to ToBoolean simply because!is defined as its negation. It’s unnecessary here, though, because it’s only used as the condition of the conditional operator, which will determine truthiness in the same way.