I ran into a scenario where JavaScript behaves in a way that is somewhat baffling to me.
Let's say we have an object with two keys foo & bar.
a = { foo: 1, bar: 2 }
Then, I have an array of strings, in this case one 'foo'
b = ['foo']
I would expect the following:
a[b] == undefined a[b[0]] == 1
BUT, this is what happens:
a[b] == 1 a[b[0]] == 1
Why does JavaScript convert ['foo'] -> 'foo'
when used as a key?
Does anyone out there know the reason?
How can this be prevented?
let a = { foo: 1, bar: 2 } let b = ['foo'] console.log(a[b] == 1) // expected a[b] to be undefined console.log(a[b[0]] == 1) // expected a[b] to be 1
An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.
toString() The toString() method returns a string representing the specified array and its elements.
For some specific functions, arrays are converted into strings. Therefore, in JavaScript, a defined method is used for the conversion of arrays into a string. JavaScript allows returning the values of an array into a string by using the “toString()” method.
Stringify a JavaScript ArrayUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(arr);
All the object keys are string, so it eventually convert everything you place inside [] (Bracket notation)
to string, if it's an expression it evaluates the expression and convert it's value to string and use as key
console.log(['foo'].toString())
Have a look at this example to understand, here [a]
eventually converts a toString using a.toString()
and then set it as key to b
object
let a = { a : 1} let b = { [a] : a } // object converted to string console.log(a.toString()) // object built using [] computed property access console.log(b)
How can i stop this
In practical scenarios you should never do this, but just to illustrate, you can intercept or override the toString
method of your object and return value as string with []
around:
let a = { foo: 1, bar: 2 } let b = ['foo'] b.toString = function() { let string = this.join(',') return "[" + string + "]" } console.log(b.toString()) console.log(a[b])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With