6

Suppose I have an object

obj = {
  a : 1
}

I'm able to access property a via obj["a"] but I'm also able to access it via obj[["a"]]. How is that possible?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
yogupta
  • 188
  • 1
  • 3
  • 9
  • 1
    Related: [Keys in Javascript objects can only be strings?](https://stackoverflow.com/q/6066846/4642212), [Using Object as key results always in value of last assignment](https://stackoverflow.com/q/53668796/4642212). – Sebastian Simon Nov 16 '19 at 12:38

1 Answers1

7

Object keys are always strings (or, rarely, symbols). When you do

obj[<expression>]

the interpreter will try to turn expression into a valid key, if it isn't one already. In this case, turning ["a"] into a string results in "a", so both obj["a"] and obj[["a"]] work.

(When an array is implicitly turned into a primitive, like here, it gets .joined by a comma, and ["a"].join(',') === "a")

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 2
    I had never realised JS was casting types as deep as it can in nested arrays: `[[[["a"]]]] == "a"` evaluates to `true` – Clepsyd Nov 16 '19 at 12:16
  • While we are on it, why does JS do it this way? – yogupta Nov 16 '19 at 12:43
  • @YogeshGupta As opposed to what, throwing an error? Some of it has to do with JS being loosely typed - the interpreter may *try* to do type conversions automatically to get to a result without throwing. It's kind of confusing, which is why I prefer Typescript, which will forbid such implicit casting – CertainPerformance Nov 16 '19 at 12:46