Last active
August 29, 2015 14:08
-
-
Save royling/c15ba8dc8e7203f652b5 to your computer and use it in GitHub Desktop.
#explain-js-type-coercion-in-js: convert to boolean
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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