Created
October 12, 2012 00:11
-
-
Save obenjiro/3876550 to your computer and use it in GitHub Desktop.
Smallest function argument validation
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
//smallest function argument validation + throwing an error if wrong type | |
//is string | |
var a = ""; | |
a.charAt(0); //OK | |
a = 1; | |
a.charAt(0); //TypeError: Object 1 has no method 'charAt' | |
//is number | |
var a = 1; | |
a.toFixed() //OK | |
a = "" | |
a.toFixed() //TypeError: Object has no method 'toFixed' | |
//is function | |
var a = function(){}; | |
a.call||undefined.f //OK | |
a = ""; | |
a.call||undefined.f //TypeError: Cannot read property 'f' of undefined | |
//is array | |
var a = []; | |
a.pop||undefined.a //OK | |
a = 1; | |
a.pop||undefined.a //TypeError: Cannot read property 'a' of undefined | |
//not null or undefined | |
var a = 0; | |
a!=null||undefined.n //OK | |
a = null; | |
a!=null||undefined.n //TypeError: Cannot read property 'n' of undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment