Arrays vs Objects
What is the difference between arrays vs objects? Both store a collection of data, but with a couple of differences.
Arrays
Arrays are a sort of object that are indexed in numerical order, starting at 0. Arrays are surrounded by square brackets.
[1, 2, 3]
Objects
Objects, or hashes, have key-value pairs. They are unordered, and are surrounded by curly brackets {}
. Object keys are always strings.
{"zero": 0, "one": 1, "two": 2}
When should we use which?
It all depends on your data and what you’re doing with it. If the order of the data is constantly changing, having an array can slow down your code significantly as that data grows. If have different types of data and need instant access to it, the key-value pairs of an object could be of benefit to you in this situation. Both have their pros and cons, but in the end, you’d have to choose the type that not only provides better performance, but is scalable.