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:
The code copy is as follows:
a=parseInt("1234")
a=”1234″-0 //Convert to number
b=1234+” //Convert to string
c=someObject.toString() //Convert object to string
Among them, the first and fourth are explicit conversions, and 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 use of two exclamation marks is to convert these values into "equivalent" Boolean values;
Let's take a look again:
The code copy is as follows:
var foo;
alert(!foo);//In undifined case, an exclamation mark returns true;
alert(!goo);//In case of null, the return of an exclamation mark is also 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 return false.