Type Detecting Function in Javascript

Here’s a simple function that detects the type of argument passed to it. Works great for overloading functions. It could probably be made more efficient but for the sake of showing how it works I intentionally made it verbose.

<script type="text/javascript">
          function detectType(random) {
              
              var output;
              
              switch(random.constructor) {
                  case Array : 
                      output = "Array ";
                      break;
                      
                  case Object : 
                      output = "Object ";
                      break;
                    
                  case Function : 
                      output = "Function ";
                      break;
                      
                  case String : 
                      output = "String";
                      break;
                      
                  case Number : 
                      output = "Number";
                      break;
                      
                  case Boolean :
                      output = "Boolean";
                      break;
                      
                  case User :
                      output = "User";
                      break;
                      
                  default : 
                      output = "Unable to determine type";
                      
              }
              
              
              
              console.debug("The type of argument is: " + output);
          }
          
          detectType("only one argument");
          
          detectType(43);
          
          detectType({
             something: "else" 
          });
          
          detectType(function () {
              var stuff = 42 + 5;
          })
          
      </script>

Simple. It uses the “constructor” property to detect the type.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.