Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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.



JavaScript: Tips of the Day

How to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

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