Logical NOT (!) - JavaScript 编辑
The logical NOT (!
) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with Boolean
(logical) values. When used with non-Boolean values, it returns false
if its single operand can be converted to true
; otherwise, returns true
.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.Syntax
!expr
Description
Returns false
if its single operand can be converted to true
; otherwise, returns true
.
If a value can be converted to true
, the value is so-called truthy. If a value can be converted to false
, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null
;NaN
;0
;- empty string (
""
or''
or``
); undefined
.
Even though the !
operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean
constructor.
Examples
Using NOT
The following code shows examples of the !
(logical NOT) operator.
n1 = !true // !t returns false
n2 = !false // !f returns true
n3 = !'' // !f returns true
n4 = !'Cat' // !t returns false
Double NOT (!!)
It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the value (see truthy and falsy).
The same conversion can be done through the Boolean
function.
n1 = !!true // !!truthy returns true
n2 = !!{} // !!truthy returns true: any object is truthy...
n3 = !!(new Boolean(false)) // ...even Boolean objects with a false .valueOf()!
n4 = !!false // !!falsy returns false
n5 = !!"" // !!falsy returns false
n6 = !!Boolean(false) // !!falsy returns false
Converting between NOTs
The following operation involving booleans:
!!bCondition
is always equal to:
bCondition
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Logical NOT expression' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论