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.



Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

Using the window.location object

JavaScript can access the current URL using the window.location object. Pretty neat, but even cooler is that this object contains certain parts of the URL as well.
Get access to the protocol/host/pathname/search/and more!

// JavaScript can access the current URL in parts. For this URL:
'https://thatsanegg.com/example/index.html?s=article'
window.location.protocol == 'https:'
window.location.host == 'thatsanegg.com'
window.location.pathname == '/example/index.html'
window.location.search == '?s=article'

Ref: https://bit.ly/2LBj213