Can We Assign a String as an Index for Array Elements in JavaScript?

Take a look at this piece of code:

let animals = [];
animals["dogs"] = 5;
animals["cats"] = 2;

console.log(animals); // prints out -> [dogs: 5, cats: 2]

Now, you might be wondering:

  • How come we're using strings as indices for an array?

  • What type are these elements in the array? They don't seem to be regular strings or numbers.

  • Is this an outdated method, and should we be using objects instead?

Let me break it down for you:

Using strings as indices for an array

Arrays are essentially objects, with their indexes being numeric object properties. They can also have additional properties that aren't numeric, including inherent ones like 'length' or custom ones such as 'cats' or 'dogs'.

Type of these elements in the array

The element values are numbers, 5 and 2. The property names, dogs and cats are strings.

All properties in JavaScript objects are either strings or symbols. Even array indices are internally stored as strings. So when you say animals[1], its the same as saying animals["1"]. Both ultimately become the string "1".

let animals = ["dog", "cat"];
console.log(Object.keys(animals)); // ["0", "1"]

Is this method outdated?

It's old, yet not outdated; however, it is not recommended.

It's just a syntax for accessing properties in objects. It's required for any property you want to access that isn't a valid identifier, including the numeric property names of array indices.


animals.1 // Error - 1 is not a valid identifier
animals[1] // Ok
animals["1"] // Ok

In fact, when it comes to the dogs and cats properties, bracket access isn't required because they're both valid identifiers. Dot syntax can be used instead.

animals.dogs = 5;
animals.cats = 2;

Arrays are just objects so they work the same way when it comes to basic property access. The only thing different about arrays from normal objects is that they have more methods for working with arrays (push, slice, map, etc.) and a somewhat magical length property that tracks the size of the as you work with properties with numeric names that are considered array indices.

At their core, they're just an object and work in all the same ways.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda