Determining Type: typeof vs instanceof

The typeof operator tells if a variable is a primitive type. It tells if a variable is a string, number, Boolean, or undefined. If the value is an object or null, then typeof returns "object":

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var s = "JavaScript"; 
        var b = true; 
        var i = 22; 
        var u; 
        var n = null; 
        var o = new Object(); 
        document.writeln(typeof s); //string 
        document.writeln(typeof i); //number 
        document.writeln(typeof b); //boolean 
        document.writeln(typeof u); //undefined 
        document.writeln(typeof n); //object 
        document.writeln(typeof o); //object 

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

To know is what type of object it is JavaScript provides the instanceof operator. Its syntax:

result = variable instanceof constructor

The instanceof operator returns true if the variable is an instance of the given reference type.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var person = new Object();
        var colors = new Array();
        document.writeln(person instanceof Object); //is the variable person an Object? 
        document.writeln(colors instanceof Array); //is the variable colors an Array? 

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Language Basics  

Variables:
  1. Primitive and reference values
  2. Determining Type: typeof vs instanceof
  3. Execution Context And Scope
  4. No Block-Level Scopes
  5. Variable Declaration with var