Introduction
JavaScript is a dynamically typed language where bindings (or variables) can hold any type at any point in time or can be changed from one type to another. Within the language, there are different types such as Number
, String
, Object
, and Boolean
.
Therefore, if a binding holds a Number
type, it can be changed or coerced into another data type like String
or Boolean
. To make it possible, there are built-in methods that allow us convert binding types such as Number()
, Boolean()
, String()
. Also, JavaScript has a language feature called type coercion.) which automatically converts values from one data type to another.
However, with Boolean, we can cast a binding (or variable) to be a Boolean type explicitly using the !!
operator and change it from one data type to a Boolean type. In this article, we will discuss how to use the double exclamation mark (!!
) or operator, and how it works.
Using double exclamation mark in JS
Within the JavaScript environment, other data type values can be cast to be a Boolean type, and you can see this when we pass values as conditional statements in a if/else
statement.
Let’s illustrate by creating some if/else
statement.
if ("") {
console.log("True");
} else {
console.log("False");
}
if ("121") {
console.log("True");
} else {
console.log("False");
}
if (1211) {
console.log("True");
} else {
console.log("False");
}
if (0) {
console.log("True");
} else {
console.log("False");
}
if ({}) {
console.log("True");
} else {
console.log("False");
}
False
True
True
False
True
From the output values, you can see that an empty string (””
), zero (0
) are coerced to false
values and non-empty strings, objects, and numbers other than zero are coerced to true
values.
Other than these values, null
, undefined
and NaN
values are coerced to false
values. Also, array
and date
values are coerced to false
values.
Knowing this, we might want to explicitly coerce a binding value to be of the Boolean
type. To achieve this, we can make use of the double exclamation mark - !!
.
const str = !!"345";
console.log(str, typeof str);
const na = !!NaN;
console.log(na, typeof na);
console.log(!!"");
Output
true boolean
false boolean
false
So, the !!
operator converts the "345"
and NaN
values to Boolean
data types based on the logic of type (Boolean) coercion
Also, you can achieve this using the Boolean
method
const str = Boolean("345");
console.log(str, typeof str);
Output
true boolean
Summary
To coerce values of a binding to Boolean
type, we can make use of the double exclamation mark and the Boolean
method. This allows us to explicitly coerce the data to the Boolean
type without relying on the automatic conversion offered by the JavaScript environment.
References
Boolean - JavaScript | MDN (mozilla.org)
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org).)