0

I have this JavaScript code

x = {"foo": "bar"};
y = {"baz": x};
z = y["baz"]["foo"];
console.log(z);

This code prints bar

x and y both objects. Then z is assigned "y" and "2 arrays". How is this assignment working? I may be reading it all wrong!

I am having a hard time understanding why it is so? Can someone please explain what's going on?

Slyper
  • 896
  • 2
  • 15
  • 32
  • 3
    It's not **2 arrays**, it's the indexing operator used twice. Read it as `(y["baz"])["foo"]` which is you first apply the first indexing operator and get `x["foo"]` and then the second and you get `bar`. – Wiktor Zychla Apr 26 '20 at 13:23
  • Hi @WiktorZychla, I didn't knew you can use letters/alphabets as an array index. Silly me. JS is such a tricky language. Make sense know. Thanks for your prompt reply. – Slyper Apr 26 '20 at 13:28
  • Hi @AlonEitan This question is not about dot vs bracket notation. I don't think its a duplicate. Not sure why it was marked duplicate? – Slyper Apr 26 '20 at 13:32
  • It's not only JS that allows you to use string indexes on indexing operators. Any language that supports dictionaries would have a similar syntax. Just think of a JS object as a dictionary that maps string literals (field names) to values. – Wiktor Zychla Apr 26 '20 at 13:49

0 Answers0