In the world of JavaScript programming, mastering the various operators and symbols is essential for writing efficient and clean code.
While many developers are well-acquainted with the single exclamation mark (!), which is used as the logical “not” operator, fewer may be familiar with its double counterpart: !!.
In this article, we will delve into the world of double exclamation marks and uncover their significance in JavaScript coding.
JavaScript Boolean Values
Before we explore the realm of !!, it’s crucial to understand how JavaScript associates boolean values with other data types.
In JavaScript, every value is implicitly associated with either true or false.
For instance:
- An empty string, such as let str = “”, is considered false.
- A number greater than zero, like const num = 9, is regarded as true.
Values that result in a true boolean association are known as truthy values, whereas those resulting in false associations are termed falsy values.
Discover more about the usage of JavaScript’s Double Question Mark Operator in our latest article!
Falsy Values in JavaScript
Here is a list of common falsy values in JavaScript:
- false
- Zero, including -0, 0.0, and hexadecimal 0x0
- Empty strings: “”, ”, or `
- Zero in BigInt type: 0n and 0x0n
- null
- undefined
- NaN
Truthy Values in JavaScript
On the other hand, some examples of truthy values include:
- An empty object: {}
- An empty array: []
- Non-empty strings: “JavaScript”
- Values greater than zero: 3.14 or 10
- Dates: new Date()
Boolean Operations in JavaScript
JavaScript often relies on boolean values rather than the values in various operations. For instance, conditional statements like the if statement or the ternary operator evaluate the associated boolean value when checking conditions.
Consider these two variables:
const str = "JavaScript";
const num = 0;
In a conditional statement, str is treated as a truthy value because it is not an empty string, while num is considered falsy because zero is a falsy value in JavaScript.
if (str) {
console.log("Hello Block One");
}
// Output: Hello Block One
if (num) {
console.log("Hello Block Two");
}
// This statement will NOT execute
The Logical “Not” Operator (!)
The logical “not” operator, denoted by !, reverses the associated boolean value of a variable. For instance:
!true // Returns: false
!false // Returns: true
By applying ! to a variable, you reverse its boolean association:
if (!str) {
console.log("Hello Block One");
}
// This block will NOT execute as the condition evaluates to false
if (!num) {
console.log("Hello Block Two");
}
// Hello Block Two - This block executed because the condition evaluates to true
In summary, the ! operator serves two primary functions:
- It checks the associated boolean value of a variable.
- It returns the opposite of the associated boolean value.
Double Exclamation Marks (!!)
Now, let’s unravel the mystery of double exclamation marks, !!. When you apply two exclamation marks to a variable, an Interesting logic unfolds:
- The first exclamation mark casts the variable’s value to a boolean and returns the opposite of its associated boolean value.
- The second exclamation mark inverts the returned boolean value.
Consider this code snippet:
const marks = 13;
console.log(!marks); // Returns false
console.log(!!marks); // Returns true
Here, !! first reverses the associated boolean value of marks (which is true) and then inverts that result.
Let’s explore more examples:
!!false // Returns false
!!true // Returns true
!!0 // Returns false (zero is falsy)
!!1 // Returns true (a number greater than 0 is truthy)
!!"" // Returns false (an empty string is falsy)
!!undefined // Returns false (undefined is falsy)
!!null // Returns false (null is falsy)
!!{} // Returns true (an empty object is truthy)
!![] // Returns true (an empty array is truthy)
const points = 40;
!!points // Returns true
const city = " ";
!!city // Returns false
Why Use Double Exclamation Marks?
You might wonder why we need !!, especially when a value is already falsy. Consider the following code:
const schoolName = " ";
Question: If schoolName is an empty string and thus falsy, why use the double bang operator (!!schoolName) when it will return false, mirroring its original state?
The answer lies in the distinction between Truthy-Falsy and True-False in JavaScript.
An empty string is indeed falsy, and in a conditional if statement, it evaluates to false. However, it remains an empty string. By applying double exclamation marks, you explicitly cast the variable to a boolean, in this case, false.
Consequently, when used in a conditional statement, it represents the literal value of false, not an empty string. In essence, double exclamation marks are used to explicitly convert a variable to a boolean.
Another reason to employ double exclamation marks is their efficiency. According to the Airbnb JavaScript documentation, using !! is considered the best method to cast a variable to a boolean among three options ranging from bad to good to best.
Curious about the mysterious double question mark in JavaScript? Dive deeper into its secrets by exploring more here!
Real-World Application of Double Exclamation Marks
To illustrate the practical use of !!, imagine developing a web application that retrieves user details (e.g., username) from a database and stores this value as a boolean:
const name = getUserName(userID);
const userName = !!name;
// If the userID exists in the database, userName will be true
Here, userName stores the boolean value of the name, which can be either true or false.
Conclusion
In this comprehensive guide, we’ve explored truthy and falsy values, the logical “not” operator (!), and the double exclamation marks in JavaScript.
Double exclamation marks, or the double bang, play a crucial role in casting values to their truthy or falsy counterparts, allowing developers to work efficiently with boolean representations of their data. Understanding and utilizing !! can enhance your JavaScript coding skills and contribute to writing more readable and efficient code.
So, the next time you encounter !!, you’ll know it’s not just a random set of characters but a powerful tool in your JavaScript arsenal.
Leave a Reply