Home  >  Article  >  Web Front-end  >  Understand the difference between ! and !! in JavaScript in one article!

Understand the difference between ! and !! in JavaScript in one article!

青灯夜游
青灯夜游forward
2020-06-24 14:01:562108browse

This article will talk to you about the difference between ! and !! in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone. The usage of ! in

Understand the difference between ! and !! in JavaScript in one article!

js is relatively flexible. In addition to doing logical operations, it often uses <span style="font-family:monospace">!</span> for type judgment. You can use ! with the above object to obtain a Boolean value.

1, ! can convert variables into boolean type, null, undefined and empty The negation of the string is false, and the rest is true.

!null=true
!undefined=true
!&#39;&#39;=true
!100=false
!&#39;abc&#39;=false

2, !! is often used to make type judgments. After the first step! (variable), the logical inversion operation is performed. In js, novices often write such bloated Code:
Only when the variable a is judged to be non-empty, undefined or non-empty can the content of the method body be executed.

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

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

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

Achieve the same effect as above. Only when a is a variable with actual meaning, the method will be executed. Otherwise, the following code will not be executed if the variables null, undefined and '' are empty strings.

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

Recommended tutorial: "JS Tutorial"

The above is the detailed content of Understand the difference between ! and !! in JavaScript in one article!. For more information, please follow other related articles on the PHP Chinese website!

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