What does the double exclamation mark (!!) operator do in JavaScript? I encountered this code snippet:
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
It appears to be using !! as an operator, which I’m not familiar with. Can you explain what this operator does and how it works in JavaScript?
The double exclamation mark (!!) operator in JavaScript is a shorthand method to convert any value to its boolean equivalent. It works by applying the logical NOT operator twice - first converting the value to a boolean and negating it, then negating the result back to the original boolean value. This operator is commonly used to ensure consistent boolean evaluation when working with truthy and falsy values.
Contents
- Understanding the Double Exclamation Mark Operator
- How the !! Operator Works
- Truthy and Falsy Values
- Practical Examples
- Comparison with Boolean() Function
- Common Use Cases
- Performance Considerations
Understanding the Double Exclamation Mark Operator
The double exclamation mark (!!) operator is not a standalone operator in JavaScript - it’s actually two logical NOT operators (!) applied sequentially. This technique is often called the “double bang” operator by developers. The primary purpose of this operator pattern is to convert any JavaScript value to its boolean equivalent.
As explained in the Stack Overflow discussion, the !! operator is essentially a shorthand method to cast variables to be a Boolean (true or false) value. This pattern is particularly useful when you need to explicitly work with boolean values rather than relying on JavaScript’s truthy/falsy evaluation.
How the !! Operator Works
The double exclamation mark operator works through a two-step process:
- First ! operator: Converts the value to a boolean and negates it
- Second ! operator: Negates the result again, returning the original boolean value
Let’s break this down with a concrete example:
const value = "hello";
const result = !!value;
// Step 1: !"hello" → !true → false
// Step 2: !false → true
// Final result: true
As the SourceBae blog explains, the unary ! operator converts its operand to a Boolean and negates it. This fact leads to the double exclamation mark pattern being equivalent to Boolean() function behavior.
The key insight is that the !! operator essentially strips away the original value type and returns a pure boolean representation of whether the value is “truthy” or “falsy” in JavaScript.
Truthy and Falsy Values
JavaScript has specific rules for what values are considered “falsy” (convert to false) and “truthy” (convert to true):
Falsy Values
false- the boolean false valuenull- the absence of any valueundefined- a variable declared but not assigned0- the number zero-0- negative zeroNaN- Not-a-Number""- empty string
All other values in JavaScript are considered truthy, including:
- Non-empty strings
- Non-zero numbers
- Objects (including arrays and functions)
- Dates
- Any other non-null, non-undefined value
As shown in the DEV Community explanation, you can see how different values behave:
// Falsy values
console.log(!!null) // false
console.log(!!0) // false
console.log(!!undefined) // false
console.log(!!"") // false
console.log(!!NaN) // false
// Truthy values
console.log(!!"dwd") // true
console.log(!!5) // true
console.log(!![]) // true
console.log(!!{}) // true
Practical Examples
Let’s examine the code snippet from your question:
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
Here’s what happens with this code:
- First, it checks if
verticalis notundefined - If true, it applies the !! operator to convert
verticalto a boolean - If false (vertical is undefined), it keeps the current
this.verticalvalue
This pattern ensures that whatever value vertical contains, it gets converted to a proper boolean value before being assigned.
Example Scenarios:
// When vertical is a number
let vertical = 42;
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
// !!42 converts to true
// this.vertical becomes true
// When vertical is an empty string
let vertical = "";
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
// !!"" converts to false
// this.vertical becomes false
// When vertical is null
let vertical = null;
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
// !!null converts to false
// this.vertical becomes false
// When vertical is undefined
let vertical = undefined;
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
// The condition is false, so this.vertical remains unchanged
Comparison with Boolean() Function
The !! operator is functionally equivalent to the Boolean() constructor function, but there are some differences:
// Both produce the same result
!!"hello" === Boolean("hello") // true
!!0 === Boolean(0) // true
!!null === Boolean(null) // true
!!undefined === Boolean(undefined) // true
However, there are some subtle differences:
Performance
The !! operator is generally faster than Boolean() because it’s a simple bitwise operation, while Boolean() involves function call overhead.
Type Conversion Behavior
Both handle the same set of values in the same way, but Boolean() can sometimes have different behavior when called with objects.
Readability
!!valueis more concise and common in modern JavaScript codeBoolean(value)is more explicit and self-documenting- Some developers find !! confusing, while others appreciate its brevity
According to the GitHub gist comparing the two approaches, both methods achieve the same result of boolean type conversion.
Common Use Cases
The double exclamation mark operator is commonly used in several scenarios:
1. Explicit Boolean Conversion
When you need to ensure a value is treated as a boolean in conditional statements:
function isValid(user) {
return !!user && !!user.name && !!user.email;
}
2. Function Return Values
When functions need to return consistent boolean values:
function hasPermission(permissions, requiredPermission) {
return !!permissions && permissions.includes(requiredPermission);
}
3. Property Existence Checks
As mentioned in your example, it’s useful for checking if properties exist and converting them to booleans:
const config = {
enabled: true,
debug: false,
logging: undefined
};
// Convert all config values to booleans
const booleanConfig = {
enabled: !!config.enabled, // true
debug: !!config.debug, // false
logging: !!config.logging // false
};
4. Array/Object Checks
When working with collections and wanting to check if they contain items:
const items = [];
const hasItems = !!items.length; // false
const users = [{name: "John"}];
const hasUsers = !!users.length; // true
Performance Considerations
The double exclamation mark operator is generally very performant in JavaScript:
Speed
The !! operator is a simple bitwise operation that’s optimized by JavaScript engines. It typically outperforms Boolean() function calls due to the absence of function call overhead.
When to Use
- Use !! when performance is critical and you need fast boolean conversion
- Use Boolean() when code readability is more important than micro-optimizations
- Consider context - in most applications, the difference is negligible
Notable Performance Difference
As noted in various sources, the performance difference between !! and Boolean() is usually only noticeable in performance-critical code or when the operation is performed millions of times.
Conclusion
The double exclamation mark (!!) operator is a powerful and concise way to convert any JavaScript value to its boolean equivalent. By applying the logical NOT operator twice, it effectively strips away the original value type and returns true or false based on JavaScript’s truthy/falsy rules. This operator is particularly useful in scenarios where explicit boolean values are required, such as in your example code that ensures consistent boolean type assignment. While functionally equivalent to the Boolean() constructor, the !! operator offers better performance and is widely adopted in modern JavaScript development for its brevity and efficiency.
Sources
- How does the double exclamation (!!) work in JavaScript? - Stack Overflow
- What’s the double exclamation mark for in JavaScript? - Medium
- Double exclamation marks in Javascript 🧐 - Medium
- JavaScript double exclamation mark explained (with examples) - DEV Community
- What’s the double exclamation mark for in JavaScript? - Brian Love
- What does the double exclamation mark operator do in JavaScript? - Stack Overflow
- What does the double exclamation mark operator do in JavaScript? - SourceBae
- The Double Exclamation Operator (!!) in JavaScript - codingem.com
- Cleaning up Your JavaScript: The Double Bang (!!) - John Kavanagh
- JavaScript | How Double Bangs (Exclamation Marks) !! Work - Become A Better Programmer