Tag Archives: Functions

Using Objects like Arrays in JavaScript.

In some situations, there can be a lot of advantages of using Objects instead of Arrays in JavaScript.
But some of programmers just don’t like objects! Here I don’t want to enter this debate about why or what! I just want to show you how to use a JavaScript Object like an Array!

So one of the very useful methods of Arrays (in JavaScript! otherwise it’s just the opposite side let’s say in Java for example!) is that you can get and set the length of any array any-time you want! then you can iterate between items inside the array and do literally any thing you want (you can do this because you know the length!).

And you can do the exact (well in pragmatic point of view) same thing in new versions of JavaScript with Objects too! using the Keys function:


But you should know that: first of all this wasn’t there in older versions of JavaScript (So your code wouldn’t function properly in old IE browsers for instance) and secondary, in proprietary / customized versions of JavaScript that aren’t that fast to get up to date with the advances of JavaScript, you won’t probably have it even in the future! (for example in Adobe products they are still using VERY old versions of JS in their VERY modern products), so what can you do about it?

Here is the solution!
If your problem is old browsers / IE, you can use sophisticated Amazon solution which will make the functionality available in most of the older browsers /IE:

Please note that you can use this function in other environments as well, but it would be a little bit over-kill since in embedded systems for example you may know most of the times the version of JavaScript and if it’s available or not so you don’t need to and probably shouldn’t check it!

And for the environments, where you know that uses an older version of JavaScript and/or this function doesn’t exist, you can write a very simple function yourself that will tell you the length of the object properties and the key values (since knowing only the length won’t help you, since you can’t access properties by index!) like so:

Here by passing an object to this function you will get back an array of Object property keys and of-course you can get the length from it like a simple array as well!

As you see it is a super simple and very short function!

See you later, mim, 😉