1

Started learning javascript and currently going thru object topic.

<!DOCTYPE html>
<html>
<body>
<h3>object prop access</h3>
<p id="demo"></p>
<p id="test"></p>
<script>

    var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
    object[foo] = 'value1';

    //console.log(object[bar]);
    document.getElementById("demo").innerHTML = "Object property:"+object[bar];
    document.getElementById("test").innerHTML = "Object property object[foo]:"+object[foo];

    </script>
    </body>
    </html>

When I run this program it prints value "value1" , "value1" in separate lines. My question is there is no property name "bar" defined for "object" then why object[bar] prints value "value1" - which is assigned to object[foo].

--Divyesh

1 Answer 1

6

Because an object property has a key and a value. The key is always a string. When you try to set a key for a value for which that key is a variable and it as an object, it will have the .toString method of the object/variable called which is this case is will return [object Object]

so bar and foo will be equivalent when converted to a string.

So, you can think of it as accessing the object like this object["[object Object]"]

bar.toString() // "[object Object]"

foo.toString() // "[object Object]"

2
  • Thanks for your reply. I tested this toString() method behaviour by printing object "Foo" and "Bar". However my question is code above sets property of object[foo] = "value1". There is no property "Bar" defined for object "Object". How can the object[Bar] = "value1" too? Commented Nov 22, 2015 at 9:03
  • I understood your point now.. Thanks a lot. I see that basically object[foo] or object[bar] is equivalent to object["[object Object]"]. So if object[foo] = "value1" so it object[bar]. Commented Nov 22, 2015 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.