JavaScript interview question

What is the purpose of double exclamation?

Answer

The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.

For example, you can test IE version using this expression as below,

let isIE11 = false;
isIE11 = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
console.log(isIE11); // returns true or false

If you do not use this expression then it returns the original value.

console.log(navigator.userAgent.match(/Trident.*rv[ :]*11\./));  // returns either an Array or null

Note: The expression !! is not an operator, but it is just twice of ! operator.

More Technical Interview Topics