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

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

青灯夜游
Release: 2020-06-24 14:04:26
forward
2182 people have browsed it

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
Copy after login

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有内容才执行的代码 
}
Copy after login

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

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

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template