What is !! (double negation) operator in javascript?

Those who are new to javascript might find this language little weird and to make this more confusing is understanding !! (double negation) operators use.

You may already or may have not seen the use of !! operator some where. But what does it actually does.

Why do we use !! operator in javascript?.

Suppose we have an expression which returns a result. Now this result can be of any type like object, NaN, string, number or whatever.

But we want this result to be a boolean value true or false.

This is where we use !!.

Actually there is only ! operator in javascript and we use it twice to get the boolean result from any expressions output.

It first negates the outcome of the expression and then negates it again. In this way if you had a non-zero number, a string, an object, an array, or anything that’s truthy, you’ll get true back.

Otherwise you’ll get false.

Checkout the below example for better understanding.

Suppose there are two variables which you want to subtract but you are not aware of the value you will get. In that case we can use !! to check the value.

//Case 1
let a = 2, b = 1;
let c = a - b; // 1
if(!!c){
  console.log('This is true');
}
'This is true';

//Case 2
let a = 'abc', b = 'xyz';
let c = a - b; //NaN
if(!!c){
  console.log('This is true');
}
//!!c gives false