Skip to content

Instantly share code, notes, and snippets.

@obenjiro
Created October 12, 2012 00:11
Show Gist options
  • Save obenjiro/3876550 to your computer and use it in GitHub Desktop.
Save obenjiro/3876550 to your computer and use it in GitHub Desktop.
Smallest function argument validation
//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