Coding Languages/JavaScript

[JavaScript] double exclamation mark (!!)

brightlightkim 2022. 4. 19. 05:29

! is the logical negation or "not" operator. !! is ! twice. It's a way of casting a "truthy" or "falsy" value to true or false, respectively. Given a boolean, ! will negate the value, i.e. !true yields false and vice versa. Given something other than a boolean, the value will first be converted to a boolean and then negated. For example, !undefined will first convert undefined to false and then negate it, yielding true. Applying a second ! operator (!!undefined) yields false, so in effect !!undefined converts undefined to false.

In JavaScript, the values false, null, undefined, 0, -0, NaN, and '' (empty string) are "falsy" values. All other values are "truthy."(1):7.1.2 Here's a truth table of ! and !! applied to various values:

 value     │  !value  │  !!value
━━━━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━━
 false     │ ✔ true   │   false
 true      │   false  │ ✔ true
 null      │ ✔ true   │   false
 undefined │ ✔ true   │   false
 0         │ ✔ true   │   false
 -0        │ ✔ true   │   false
 1         │   false  │ ✔ true
 -5        │   false  │ ✔ true
 NaN       │ ✔ true   │   false
 ''        │ ✔ true   │   false
 'hello'   │   false  │ ✔ true

from https://stackoverflow.com/questions/29312123/how-does-the-double-exclamation-work-in-javascript

'Coding Languages > JavaScript' 카테고리의 다른 글

[JavaScript] Strict inequality (!==)  (0) 2022.04.23
[JavaScript] Map  (0) 2022.04.20
[JavaScript] RegExp  (0) 2022.04.16
[JavaScript] Promise.resolve()  (0) 2022.04.16
[JavaScript] Curry and Function Composition  (0) 2022.04.15