Just seen a piece of javascript code where they placed two exclamation marks in front of a variable and I'm not sure what it does. I know what one does in front of a variable, just not what the second does. Any ideas would be much appreciated.
Asked
Active
Viewed 1,087 times
1 Answers
-4
From: http://brianflove.com/2014/09/02/whats-the-double-exclamation-mark-for-in-javascript/
function() {
var nothing = "";
if (nothing) {
window.alert('Nothing');
} else {
window.alert('Huh?');
}
}
When the function above is executed we will get the alert “Huh?” because the value of the variable hello is being evaluated to be false. This is what is commonly referred to as truthy versus falsey.
The following values are considered by JavaScript to be falseys:
Empty string: “”
0
null
undefined
NaN
The following values are considered by JavaScript to be truthys:
Object: {}
Array: []
Not empty string: “anything”
Number other than zero: 3.14
Date: new Date();
The JavaScript engine that is executing your code will attempt to convert (or coerce) a value to a boolean when necessary, such as when evaluated in an if-statement.
So, why double exclamation marks?
In some cases you may want to cast a variable to be explicitly boolean. Why? Well, the number one reason is that most of time developers do not use type safe comparison operators.
The type safe comparison operators are:
Strictly equal: ===
Strictly unequal: !==
When using the type safe comparison operators you are both checking that the values are equal (or unequal) and that their type is the same. Without the type safe comparison operators, you are allowing the JavaScript engine the freedom to coerce your variables to true or false based on the truthy/falsey logic.
To cast your JavaScript variables to boolean, simply use two exclamation signs:
function() {
var name = "Brian";
//alert 'string'
window.alert(typeof name);
//cast to boolean
var bool = !!name;
//alert 'boolean'
window.alert(typeof bool);
}
In the example code above we are casting the string “Brian” to a boolean value. Therefore the second alert will indicate that the variable is now a boolean value.

John Z
- 26
- 9