Please help me understand how bracket notations work in the background.
Recently in a JavaScript interview, I have come across a question and when I tried solving using bracket notations, I was told that it is a very expensive operation and shouldn't be used. I didn't get more clarifications on this.
let arrayValue = ['a', 'c', 'c', 'z', 'a', 'b', 'd', 'c']
obj = {}
for (const v of arrayValue) {
if (!obj[v]) {
obj[v] = 1
} else {
obj[v] = obj[v] + 1
}
}
console.log(obj)
When I started exploring bracket notations, I found that if I use numbers instead of strings, it sorts and rearrange the object in ascending order. But it doesn't sort it for strings.
let arrayValue = [100, 2, 4, 98, 45, 34, 67, 23, 87, 4, 19, 6, 8]
obj = {}
for (const v of arrayValue) {
if (!obj[v]) {
obj[v] = 1
} else {
obj[v] = obj[v] + 1
}
}
console.log(obj)
I understand that according to MDN, even if I am adding a key as a number it will be converted to a string.
Bracket notation
In the
object[property_name]
syntax,property_name
is just a string or Symbol. So, it can be any string, including1foo
,!bar!
, or even(a space).
But I am not able to find out how adding key as random numbers are automatically sorting the Object as you can see in the 2nd code snippet. I have tried exploring google, MDN documents and other resources but couldn't find out, how it is done in the background.
Is it using any sorting algorithm in the background, if so why only numeric inputs are only sorted but not alphabetic inputs? Additional information like time complexity information will also help me. If you can point me to any documentation where I can read about all the information I am looking for, that will also be helpful.
Thanks in advance.