w3resource

JavaScript: instanceof Operator

Description

The instanceof operator is used to check the type of an object at run time. The instanceof operator returns a boolean value that indicates if an object is an instance of a particular class.

Syntax

var result = objectName instanceof objectType

Parameters

objectName: Name of the Object.

objectType: The type of the object.

Example:

The following web document shows how the instanceof operator is used.

HTML Code

<!doctype html><head>
<meta charset="utf-8">
<title>JavaScript instanceof operator example</title>
<meta name="description" content="This document contains an example of JavaScript instanceof 
operator"/>
</head>
<body>
<script src="javascript-instanceof-operator-example1.js"></script>
</body>
</html>

JS Code

var string1 = "w3resource"; //Declaring string object
var date1 = new Date();  //Declaring Date object
if (string1 instanceof String) 
{
var newParagraph = document.createElement("p");
var newText = document.createTextNode('The type of string1 object is String'); 
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph); 
}
if (date1 instanceof Date)
{
var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode('The type of date1 object is Date'); 
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);
}

View the example in the browser

Practice the example online

See the Pen instanceof-1 by w3resource (@w3resource) on CodePen.


Previous: JavaScript: in Operator
Next: JavaScript: new Operator

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.