A while back I wrote a few functions to reliably determine types in javascript. The reason I made these functions is because javascript’s typeof operator doesn’t always return what you want. The main idiosyncrasy is typeof [] and typeof null both returning "object".

At the time of coding, I also wanted a function to tell me whether something was an integer, something javascript doesn’t support natively on its own. Of course, it doesn’t actually tell you if it’s an integer, merely whether it has a fraction part.

  1. function isInteger(val) {
  2. return isNumber(val) && Math.floor(val) == val;
  3. }
  4.  
  5. function isNumber(val) {
  6. return typeof val == "number";
  7. }
  8.  
  9. function isString(val) {
  10. return typeof val == "string";
  11. }
  12.  
  13. function isBoolean(val) {
  14. return typeof val == "boolean";
  15. }
  16.  
  17. function isObject(val) {
  18. return typeof val == "object" && val !== null;
  19. }
  20.  
  21. function isArray(val) {
  22. return val instanceof Array;
  23. }
  24.  
  25. function isFunction(val) {
  26. return typeof val == "function";
  27. }
plain