Skip to content
Related Articles
Open in App
Not now

Related Articles

How to check if the provided value is an object created by the Object constructor in JavaScript ?

Improve Article
Save Article
  • Last Updated : 15 Feb, 2023
Improve Article
Save Article

In this article, we will learn how to check if the provided value is an object created by the Object constructor in JavaScript. Almost all the values in JavaScript are objects except primitive values.

Approach: We know that an object will have its own properties and methods. For any JavaScript object, there is a property known as the constructor property. This constructor property basically returns a reference to the constructor function that created the instance. For example, the constructor property of an array will return Array as the result. Similarly, for an object, it will return an Object. Note that these do not string values, rather references to the constructor function. 

The checking of a value, if it was created by the Object constructor, can simply be done by comparing the object’s constructor property value with the corresponding Object constructor function reference. This returns a boolean value depending upon the result of the comparison.

Syntax:

return (obj.constructor === Object);

Example:

HTML




<h1 style="color: green;">
    GeeksforGeeks
</h1>
<h3>How to check whether an object is
    created by Object constructor or not</h3>
<p>Click on the button to run all test cases</p>
  
<p>Test Case 1: {}</p>
  
<p>Created by Object constructor:
    <span id="testcase1"></span>
</p>
<p>Test Case 2: new Object</p>
  
<p>Created by Object constructor:
    <span id="testcase2"></span>
</p>
  
<p>Test Case 3: new Object()</p>
  
<p>Created by Object constructor:
    <span id="testcase3"></span>
</p>
  
<p>Test Case 4: []</p>
  
<p>Created by Object constructor:
    <span id="testcase4"></span>
</p>
  
<p>Test Case 5: "GeeksforGeeks"</p>
  
<p>Created by Object constructor:
    <span id="testcase5"></span>
</p>
  
  
<button onclick="executeTestCases()">Run</button>
<script>
    // Function to check if created by
    // Object constructor
    function checkCreatedByObjectConstructor(obj) {
      return obj.constructor === Object ? true : false
    }
      
    function executeTestCases() {
      document.getElementById("testcase1").textContent =
        checkCreatedByObjectConstructor({});
      
      document.getElementById("testcase2").textContent =
        checkCreatedByObjectConstructor(new Object);
      
      document.getElementById("testcase3").textContent =
        checkCreatedByObjectConstructor(new Object());
      
      document.getElementById("testcase4").textContent =
        checkCreatedByObjectConstructor([]);
      
      document.getElementById("testcase5").textContent =
        checkCreatedByObjectConstructor("GeeksforGeeks");
    }
</script>

Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!