Javascript Type of Operator

The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to “number”, “string”, or “boolean” if its operand is a number, string, or boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.

TypeString Returned by typeof
Number“number”
String“string”
Boolean“boolean”
Object“object”
Function“function”
Undefined“undefined”
Null“object”

Example

The following code shows how to implement typeof operator.

<html>
   <body>
      
      <script type="text/javascript">
         <!--
            var a = 10;
            var b = "String";
            var linebreak = "<br />";
         
            result = (typeof b == "string" ? "B is String" : "B is Numeric");
            document.write("Result => ");
            document.write(result);
            document.write(linebreak);
         
            result = (typeof a == "string" ? "A is String" : "A is Numeric");
            document.write("Result => ");
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>

Output

Result => B is String 
Result => A is Numeric
Set the variables to different values and different operators and then try...

Leave a Reply