Home > Web Front-end > JS Tutorial > Introduction to the usage of ! and!! in js

Introduction to the usage of ! and!! in js

王林
Release: 2020-05-16 09:27:23
forward
2133 people have browsed it

Introduction to the usage of ! and!! in js

The usage of ! in js is relatively flexible. It is often used in addition to doing logical operations! It can be used for type judgment! To obtain a Boolean value with the above object,

1,! can convert the variable into a boolean type. The negation of null, undefined and empty string is false, and the others are true.

!null=true
!undefined=true
!''=true
!100=false
!'abc'=false
Copy after login

2.! ! It is often used for type judgment. 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, undefined or non-null String can execute the content of the method body

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

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

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

to 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.

It 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 the negation operation of logical AND, especially the latter in The code is concise and efficient when judging the type, eliminating the need for redundant code to judge null, undefined and empty strings multiple times.

Recommended tutorial: js introductory tutorial

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

Related labels:
js
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