Home >Web Front-end >JS Tutorial >Learn the difference and usage of ! and!! in js

Learn the difference and usage of ! and!! in js

coldplay.xixi
coldplay.xixiforward
2020-06-29 17:34:412061browse

Learn the difference and usage of ! and!! in js

I discovered this usage when looking at other people’s js code:

if (!!item.value) {
	param[item.name] = item.value;
}

I haven’t studied js for a long time, so I quickly added it and found a Very fun stuff.

Recommended learning tutorial: javascript video tutorial

The usage of ! in js is relatively flexible, and it is often used in addition to doing logical operations! It can be used for type judgment! Use the above object to obtain a Boolean value,
1,! Variables can be converted to boolean type. The negation of null, undefined and empty string is true, and the others are false.

!null=true

!undefined=true

!''=true

!100=false

!'abc'=false

2,! ! is often used to make type judgments. After the first step! (variable), the logical negation operation is performed. In js, novices often write such bloated code:
Determine whether variable a is non-null and undefined. Or the content of the method body can only be executed if it is not an empty string.

var a;
if(a!=null&&typeof(a)!=undefined&&a!=''){
    //a有内容才执行的代码  
}

In fact, we only need to write a judgment expression:

if(!!a){
    //a有内容才执行的代码...  
}

to achieve the same effect as above. Only when a is a variable with actual meaning, the method will be executed. Otherwise, variables null, undefined and '' "empty string will not execute the following code.

can be summarized, "! " is a logical AND operation, and can be logically ANDed with any variable to convert it into a Boolean value. "!!" is the negation operation of logical AND, especially the latter's code is simple and efficient when judging types, eliminating the need for multiple times Redundant codes for judging null, undefined and empty strings.

So in the code at the beginning, !!value , first convert the value into an inverted Boolean value, and then invert the obtained Boolean value again to ensure When the value of value is null, undefined or an empty string, the code in the if body will not be executed.

???Another interesting thing discovered???:

(!(~ []) {})[--[~ ""][ []]*[~ []] ~~! []] ({} [])[[~! []]* ~ []]

Output the result of the above js, emmmmm...? ? ? ?

?...Slip away...

The above is the detailed content of Learn the difference and usage of ! and!! in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete