!! It is generally used to cast the following expression into Boolean data (boolean), that is, it can only be true or false;
I often see examples like this:
The code copy is as follows:
var a;
var b=!!a;
a is undefined by default. !a is true, !!a is false, so the value of b is false, no longer undefined, nor other values, which mainly provides convenience for subsequent judgment.
!! It is generally used to cast the following expression into Boolean data (boolean), that is, it can only be true or false;
Because javascript is a weak-type language (variables do not have fixed data types), it sometimes needs to be cast to the corresponding type, such as:
a=parseInt("1234")a="1234"-0 //Convert to number b=1234+" //Convert to string c=someObject.toString() //Convert the object to stringAmong them, the first and fourth are explicit conversions, and the 2 and 3 are implicit conversions
Boolean conversion, JavaScript convention rules are
false, undefined, null, 0, "" is false
true, 1, "somestring", [Object] is true
For other implicitly converted values such as null and undefined, the ! operator will produce true results, so the purpose of using two exclamation marks is to convert these values into "equivalent" Boolean values;
Let's take a look again:
var foo; alert(!foo);//Undifined, an exclamation point returns true; alert(!goo);//In null, an exclamation point returns true; var o={flag:true}; var test=!!o.flag;//Equivalent to var test=o.flag||false; alert(test);This example demonstrates that when undifined and null, the return of one exclamation point is true, and the return of two exclamation points is false, so the function of the two exclamation points is that if the value of the variable is clearly set (non-null/undifined/0/" and "equivalent values), the result will be returned based on the actual value of the variable. If it is not set, the result will be returned.