How to use instanceof In Javascript

In this approach, we are using the instanceof operator to check if the object is an instance of the Object class and not an array, making sure it’s a plain JSON object.

Syntax:

let gfg = objectName instanceof objectType

Example 1: The below example uses instanceof to check if the object is json in JavaScript or not.

JavaScript
const obj = {
    name: "GFG",
    age: 30,
    city: "Noida"
};
const obj2 = ["1", "2", "3"];
const isJSON = obj instanceof Object && !Array
    .isArray(obj);
const isJSON2 = obj2 instanceof Object && !Array
    .isArray(obj2);
console.log(isJSON);
console.log(isJSON2);

Output
true
false

Example 2: Checking if ‘data’ is a JSON object and ‘arrayData’ is a JSON array using ‘instanceof’. Logging the results for verification.

JavaScript
const data = { id: 1, name: "GFG" };
const arrayData = [1, 2, 3];
const isJSONObject = data instanceof Object
    &&
    !Array
        .isArray(data);
const isArrayJSONObject = arrayData instanceof Object && !Array
    .isArray(arrayData);
console.log(isJSONObject);
console.log(isArrayJSONObject);

Output
true
false


How to Check if Object is JSON in JavaScript ?

JSON is used to store and exchange data in a structured format. To check if an object is JSON in JavaScript, you can use various approaches and methods. There are several possible approaches to check if the object is JSON in JavaScript which are as follows:

Table of Content

  • Using Constructor Type Checking
  • Using instanceof

Similar Reads

Using Constructor Type Checking

In this approach, we are using Object.prototype.toString.call(obj) to get the constructor type of the object and compare it to [object Object], making sure it’s a plain object. We also verify that the object is not an array using Array.isArray(obj), thus determining if it’s JSON-like....

Using instanceof

In this approach, we are using the instanceof operator to check if the object is an instance of the Object class and not an array, making sure it’s a plain JSON object....