flimflam57
flimflam57

Reputation: 1334

Confusing Javascript property accessors

I'm not fully getting this:

var one = {};
var two = {};
var three = {};

three[one] = "one";
three[two] = "two";

console.log(three[one]); // Alerts "two"

As I understand it, JS needs a string inside the bracket property notation. So it looks like JS is trying to change:

three[one] = "one";
three[two] = "two";

into:

three[one.toString()] = "one";
three[two.toString()] = "two";

Both toString() methods aren't defined so they end up being the same value? Not sure if I get it.

Upvotes: 2

Views: 58

Answers (2)

Musa
Musa

Reputation: 97672

Actually the toString method is defined and results in the same string for both([object Object]).

var one = {};
var two = {};
$('body').append(one.toString()+'<br>'+two.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 4

Kolby
Kolby

Reputation: 2865

var one = {};
var two = {};
var three = {};

three[one] = "one";
three[two] = "two";

The last two lines are saying:

three[object] = "one";
three[object] = "two";

Because one and two are both declared as objects.

The three object that you're making is going to look like this:

[object Object] {
  [object Object]: "two"
}

Upvotes: 2

Related Questions