javascriptobject

How to get the object name of an object in JavaScript


This is NOT about how to get keys or values

In the example below:

var exampleObject = {startIndex: 1, stopIndex: 2};

How can I get the exact name "exampleObject" of this object? I have tried exampleObject.constructor.name but all I got was "Object" as the result.


Solution

  • You cannot.*

    First of all, more than one variables can point to the same object. Variables are only references, not containers. There is no one true name for an object. Here's an example:

    function makeExample() () {
      var x = {startIndex: 1, stopIndex: 2};
      var y = x;
      return y;
    }
    
    var z = makeExample();
    

    In the above code, what should the name of the object be? x, y, z? All of these variables don't contain a copy of the object, they point to the same object. exampleObject is the name of the variable, not the name of the object.

    A variable name is just a label to be used by the programmer, not by code. That is not the same thing as a property, which is data stored inside an object and identified by a key which is either a string or a symbol. If the object needs to have a name, then it should be part of its own properties:

    var exampleObject = { name: "exampleObject" };
    

    *Technically, any variable created with var in the global scope of a script that is not executed as a module will be added to the window object. That is a relic of the past and you should not rely on this - in fact, modern JS code should use let to create variables which do not have this behavior.