Skip to content

Instantly share code, notes, and snippets.

@royling
Last active August 29, 2015 14:08
Show Gist options
  • Save royling/c15ba8dc8e7203f652b5 to your computer and use it in GitHub Desktop.
Save royling/c15ba8dc8e7203f652b5 to your computer and use it in GitHub Desktop.
#explain-js-type-coercion-in-js: convert to boolean
describe("toBoolean", function() {
var toBool = toBoolean;
it("should return true for all objects", function() {
expect(toBool({})).toBe(true);
expect(toBool([])).toBe(true);
});
it("should return false for falsy values", function() {
expect(toBool(0)).toBe(false);
expect(toBool(NaN)).toBe(false);
expect(toBool(false)).toBe(false);
expect(toBool(null)).toBe(false);
expect(toBool(undefined)).toBe(false);
expect(toBool('')).toBe(false);
});
it("should return true for truthy values", function() {
expect(toBool(1)).toBe(true);
expect(toBool(true)).toBe(true);
expect(toBool(new Object())).toBe(true);
expect(toBool('a')).toBe(true);
});
});
function toBoolean(value) {
if (typeof value == 'object' && value !== null) return true;
// NaN !== NaN
if (typeof value == 'number' && isNaN(value)) return false;
switch(value) {
// strict match
case 0:
case false:
case '':
case null:
case undefined:
return false;
default:
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment