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?

1

1 Answer 1

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")

Sign up to request clarification or add additional context in comments.

3 Comments

I had never realised JS was casting types as deep as it can in nested arrays: [[[["a"]]]] == "a" evaluates to true
While we are on it, why does JS do it this way?
@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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.