Summary: In this tutorial, you will learn about !! (not not) operator in JavaScript. You will also learn when and how to use it in your JavaScript code.
!! Operator in JavaScript
In JavaScript, the “!!” operator is a double negation, which is used to convert a value to a boolean type. It is often used as a quick way to check if a value is “truthy” or “falsy.”
For example:
!!0 // false
!!1 // true
!!null // false
!!'' // false
!!'hello' // true
The !! operator first converts the value to a boolean using the Boolean
function, and then negates it twice, which has the effect of flipping the value from true
to false
or false
to true
.
It is often used in combination with an if
statement to check if a value is truthy or falsy:
if (!!value) {
// value is truthy
} else {
// value is falsy
}
When to Use !! in JavaScript?
Here are a few more examples of how the !! operator can be used:
1. Check if a variable is defined
let x;
if (!!x) {
console.log('x is defined');
} else {
console.log('x is not defined');
}
In this example, we are using the !! operator to check if the variable x
is defined. The let
keyword is used to declare a block-scoped variable, but it is not initialized with a value. This means that x
is defined, but its value is undefined
.
The !! operator first converts the value of x
(undefined
) to a boolean using the Boolean
function, which returns false
.
The double negation then flips this value to true
, so the if
statement evaluates to true
and the code inside the block is executed.
2. Check if an object has a property
let obj = {
foo: 'bar'
};
if (!!obj.foo) {
console.log('obj has a property "foo"');
} else {
console.log('obj does not have a property "foo"');
}
In this example, we are using the !! operator to check if the object obj
has a property called foo
. The object obj
is defined with a single property, foo
, which has a value of 'bar'
.
The !! operator first converts the value of obj.foo
('bar'
) to a boolean using the Boolean
function, which returns true
.
The double negation then flips this value to false
, so the if
statement evaluates to false
and the code inside the else
block is executed.
3. Check if an array is empty
let arr = [];
if (!!arr.length) {
console.log('arr is not empty');
} else {
console.log('arr is empty');
}
In this example, we are using the !! operator to check if the array arr
is empty. The array arr
is defined as an empty array, which means that its length
property is 0.
The !! operator first converts the value of arr.length
(0) to a boolean using the Boolean
function, which returns false
.
The double negation then flips this value to true
, so the if
statement evaluates to true
and the code inside the else
block is executed.