When to quote JavaScript array keys?
I have stumbled upon a question: when you should quote JavaScript associative array keys. From this article you will learn, when you should quote and when not.
What are associative arrays in JavaScript?
JavaScript has an associative array. The difference between it and associative arrays in other languages is that… it is not precisely an array. In JavaScript what everyone means under an associative array is really an object.
But because it acts like an array, and it looks like an array, I call it associative array. Just keep in mind it is really an object.
To create an associative array in JavaScript you can use so-called object literal initializer. It goes like that:
const myVegetables = {
lettuce: 2,
tomato: 8
}
As you can see, myVegetables is created with curly braces. It contains two keys with a name of a vegetable, a number of these vegetables.
Objects in JavaScript are dualistic (you can skip that)
After creating an associative array, you can access values, like you were using an array:
console.log(myVegetables['lettuce'])