Closely related questions:
- associative array versus object in javascript
- Why does JavaScript not throw an exception for this code sample?
- javascript array associative AND indexed?
I have the following code sample:
var someVariable = {abc: "def", ghi: "jkl"}
someVariable["SomeProperty"] = "dfsdfadsd"
alert(someVariable["SomeProperty"])
var someOtherVariable = { abcd: "defsd", ghij: "dfsdfdss" }
someOtherVariable.SomeOtherProperty = "adfsdfsd"
alert(someOtherVariable.SomeOtherProperty);
alert(someOtherVariable["SomeOtherProperty"])
All of them do exactly what they look like - they attach a property to their respective objects. The alert
shows the expected string in every case. My understanding from the related questions is that there's no functional difference between the two.
I also encountered the following statements in W3Schools's JavaScript arrays tutorial:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
If that's the case, why is array syntax permitted here at all? (Again, my understanding from the related questions is that the actual distinction between an associative array and a JavaScript object is, at a minimum, slightly blurry, and that that's how JavaScript is implementing object properties "under the hood").
As far as I know (and please correct me if I'm wrong as JavaScript isn't my primary language), it's not possible to do other things you'd expect to be able to do with an array (e.g. iteration with a for
loop), so why bother having both syntaxes? In C# you can do something like:
// A C# dictionary is basically an associative array
Dictionary<string, int> dict = new Dictionary<string, int>();
// Fill dictionary ...
foreach (string key in dict.Keys) {
int value = dict[key];
// Do something with the value
}
but I'm not aware of a way to do a similar thing with JavaScript properties. There's a clear necessity for this syntax in C# (keys are definitely not properties of dict
), but why does JavaScript have this (given that they're exactly equivalent)? Am I missing something, or is this actually completely redundant?