5

Can somebody explain the behaviour of the following code?

let obj = {a:1, b:2}
let i = ['a']
console.log(obj[i])
>> 1

Why is it that even an array can be used to access a property inside an object? As a side note this only works with an array of length 1. I have tried researching this but there's no documentation as far as I know that explains why this should work.

2 Answers 2

9

Property names are always strings or symbols.

If you pass something which isn't a string or symbol, it gets converted to a string.

The default toString() method on an array is roughly:

String.prototype.toString = function () { return this.join(","); }

So ['a'] gets converted to 'a'.

As a side note this only works with an array of length 1.

It works fine with arrays that are longer. You just need a matching value:

const o = {
    "a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);


And since any object can be converted to a string, and you can customise the toString method, you can do really weird things:

const data = {
  "42": "Hello"
}

class Weird {
    constructor(x) {
        this.x = x;
    }
    toString() {
        return this.x + 40;
    }
}

const w = new Weird(2);
console.log(data[w]);

(Note that doing really weird things is usually a stupid idea that makes it hard to debug your own code two weeks later).

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

Comments

0

let obj = {a:1, b:2}

First you declare an object with 2 properties, a and b with values 1 and 2, respectively.

let i = ['a']

Then a variable i is declared, with it's value set to a string array with a single element, 'a'.

console.log(obj[i])

In this statement, the value of i is resolved to a string because the array only contains one element, as you mentioned. Due to this, 'a' is a valid property name for obj because all object properties are either strings, and if you pass something such as an array, it's converted to a string.

If you reference the variable icontaining the array, and it has multiple elements, it cannot resolve to a single property name without you being more explicit such as obj[i[0]]. If you only have one value, it'll resolves to that value.

obj['a'] is a valid property obj['a,b'] is not.

Comments

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.