Skip to content

Instantly share code, notes, and snippets.

@SorenPeterson
Last active August 25, 2016 16:02
Show Gist options
  • Save SorenPeterson/b578c93ae8bb29b85f8cc430fb27fd26 to your computer and use it in GitHub Desktop.
Save SorenPeterson/b578c93ae8bb29b85f8cc430fb27fd26 to your computer and use it in GitHub Desktop.
An explanation of why double negation is valuable.
var obj = {};
if (obj) {
// this would run because obj is truthy. See https://developer.mozilla.org/en-US/docs/Glossary/Truthy and https://developer.mozilla.org/en-US/docs/Glossary/Falsy
}
if (!!obj) {
// this would also run because obj is truthy.
// when you negate it the first time, it becomes the value false
// when you negate it the second time, it turn that false value into true
}
if (!!obj === true) {
// this runs because the double negation results in a value of true
}
if (obj === true) {
// this would NOT run, because obj (which evaluates to {}) does NOT equal the value true
}
// Here's an example of a function that expects a true value and demonstrates how the double negation is valuable
var resultFromSomeOtherFunction = {};
function aFunctionThatExpectsTrue(val) {
if (val === true) {
return 'nice!';
} else {
throw new Error('I don\'t understand the non-boolean');
}
}
aFunctionThatExpectsTrue(resultFromSomeOtherFunction); // this would throw an error
aFunctionThatExpectsTrue(!!resultFromSomeOtherFunction); // this would return the string 'nice!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment