The ! operator
The ! operator is called logical negation (NOT).
It inverts (flips) the logical value of an expression.
Rule:
javascript
!true → false
!false → trueIf a value is truthy - it becomes
false. If it is falsy - it becomestrue.
Examples of using !
javascript
!true // false
!false // true
!0 // true (0 - a falsy value)
!1 // false (1 - truthy)
!"" // true (an empty string - falsy)
!"hello" // false (a non-empty string - truthy)
!undefined // true
!null // true
!NaN // true
![] // false (an array - truthy)
!{} // false (an object - truthy)Double negation !!
A double operator is very common in JavaScript:
javascript
!!valueIt is used to coerce any value to the boolean type.
Example:
javascript
!!'hello' // true
!!'' // false
!!0 // false
!!123 // true
!!null // false
!!{} // true
!![] // true
!!is a short and clear way to explicitly say: "Convert this value to boolean".
In logical expressions
! is often used to check conditions:
javascript
const isLoggedIn = false;
if (!isLoggedIn) {
console.log('User is not authenticated');
}Here,
!isLoggedIn→!false→true, so theifblock will execute.
How it works internally
- JS first coerces the value to a logical type (
true/false); - then it inverts it.
Example:
javascript
!'text' // step 1: 'text' → true; step 2: !true → falseComparison with other logical operators
| Operator | Name | Example | Result |
|---|---|---|---|
! | Logical NOT | !true | false |
&& | Logical AND | true && false | false |
|| | Logical OR | true || false | true |
Summary
| Situation | What ! does | Example |
|---|---|---|
| Negates a logical value | !true → false | |
Coerces a value to boolean | !!'js' → true | |
| Used in conditions | if (!user) → "if user is not set" |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.