Videos
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want: You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
Which do you think looks cleaner?
object = new Array();
object.prop1 = 1;
object.prop2 = 2;
object.prop3 = 3;
or
object = {
prop1: 1,
prop2: 2,
prop3: 3
}
?
Also, if you do something like this:
if (object.length === undefined) object.length = 10
object.length // 0
Then object.length will still be 0, which is definitely not what you would expect. You might think this is just a fake example that will never come up in real life, but look at this:
words = 'You should join our club because it is a club'.split(' ')
obj = new Array()
words.forEach(function(x) {
if (obj[x] === undefined) obj[x] = 0
obj[x] ++
})
for (var x in obj) console.log(x, obj[x])
This will log:
You 1
should 1
join NaN // <-- oops
our 1
club 2
because 1
it 1
is 1
a 1
Alternatively, you could make an analogy to any other object, like a function:
object = function() {}
object.prop1 = 1;
// ...
Anyone could immediately tell you that that is wrong, and using an array is just as wrong.
That's not an associative array. That's an array object abused. It just works because arrays are also objects in JavaScript.
When you're doing arr.prop_1 = "asdf"; or arr['prop 2'] = "1234"; what you're actually doing is monkey patching an object.
People use objects as maps often - but that'll get fixed soon since ES6 (the new version of the standard JS is based on) has Map types.
When to use an Array
When you have sequential data - a list of numbers for example
When to use a map
When you want to store a key-value mapping.