JavaScript Instanceof Operator

Below is the example of the Instanceof Operator.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html> 
    <html
      
    <body
        <center
            <h1 style="color:green">GeeksforGeeks</h1
      
            <p id="GFG"></p
      
            <script
                var a = ["Geeks", "for", "Geeks"]; 
      
                document.getElementById("GFG").innerHTML = 
                    (a instanceof Array) + "<br>" + 
                    (a instanceof Number); 
            </script
        </center
    </body
      
    </html

    chevron_right

    
    

  • Output:

The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.

Syntax:

var gfg = objectName instanceof objectType

Parameters:
objectName: States the name of Object.

Example-1: objectTypes.



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    <center>
        <h1 style="color:green">GeeksforGeeks</h1>
  
        <p id="GFG"></p>
  
        <script>
            var fruits = ["Apple", "Mango", "Banana"];
  
            document.getElementById("GFG").innerHTML =
                (fruits instanceof Array) + "<br>" +
                (fruits instanceof Object) + "<br>" +
                (fruits instanceof String) + "<br>" +
                (fruits instanceof Number);
        </script>
    </center>
</body>
  
</html>

chevron_right


Output:

Example-2: Demonstrating that String and Date objects are also a type of Object (derived from Object).

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
  
    <p id="GFG"></p>
  
    <script>
        var myString = new String();
        var myDate = new Date();
  
        console.log(myString instanceof Object);
        console.log(myString instanceof Date);
        console.log(myString instanceof String);
        console.log(myDate instanceof Date);
        console.log(myDate instanceof Object);
        console.log(myDate instanceof String);
    </script>
</body>
  
</html>

chevron_right


Output

Supported Browsers:

  • Google Chrome
  • Firefox
  • Edge
  • Opera
  • Apple Safari

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.