Skip to content

Instantly share code, notes, and snippets.

@beeleebow
Last active April 3, 2016 03:25
Show Gist options
  • Save beeleebow/e6366cc7c78d61d8e39e to your computer and use it in GitHub Desktop.
Save beeleebow/e6366cc7c78d61d8e39e to your computer and use it in GitHub Desktop.
A set of examples that remind me how Boolean coercion works in JavaScript
var truthTest = function(value){
return value ? "true" : "false";
}
// Boolean literals behave as expected
var trueLiteral = true;
var falseLiteral = false;
truthTest(trueLiteral); // true
truthTest(falseLiteral); // false
// null and undefined are always coerced to false
var nullLiteral = null;
var undefinedVariable;
truthTest(nullLiteral); // false
truthTest(undefinedVariable); // false
// strings are coreced to false if their length is zero or if the string itself
// is a representation of false (in any casing), true otherwise
var emptyString = '';
var nonEmptyString = 'hello';
var stringRepresentationOfFalse = 'FaLsE';
truthTest(emptyString); // false
truthTest(nonEmptyString); // true
truthTest(stringReprestationOfFalse); // false
// numbers are coerced to false if zero or NaN, true otherwise
var zero = 0;
var NaNLiteral = NaN;
var nonZeroNumber = 5;
truthTest(zero); // false
truthTest(NaNLiteral); // false
truthTest(nonZeroNumber); // true
// objects (including arrays) are coerced to true
var emptyObj = {};
var nonEmptyObj = { x: 1 };
var emptyArray = [];
truthTest(emptyObj); // true
truthTest(nonEmptyObj); // true
truthTest(emptyArray); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment