instanceof in JavaScript

instanceof operator returns a Boolean value that indicates whether or not an object is an instance of a particular class

Example 1: To check if a object is an instance of String Class
<script type="text/javascript">

var color1 = new String("green");
document.write(color1 instanceof String); // returns true

var color2 = "coral";
document.write(color2 instanceof String); // returns false (color2 is not a String object) // returns false


</script>


Example 2 : Check if the exception inherits from Syntax Error
<script type="text/javascript">
try {
    eval("a ++ b");        //causes SyntaxError
} catch (oException) {
    if (oException instanceof SyntaxError) {
        alert("Syntax Error: " + oException.message);
    } else {
        alert("An unexpected error occurred: " + oException.message);
    }
}
</script>


Note : instanceof operator works only when the new operator is used, Hence the following code returns false.
<script type="text/javascript">
var color1 = String("green");
document.write(color1 instanceof String); // returns false
</script>