0

In situations of storing sets of values, should objects really be used in Javascript? In this case, I don't see an advantage of using an object over using an array. Although logic dictates its only preference, I can't shake the feeling that there's something I don't see.

Here is my example. Lets say we have have a bunch of cars, each car contains data with a specific format:

{
    model: '';
    color: '';
    max_speed: '';
}

And we have a few functions, for which the (somewhat terse) pseudo code is:

function compareCarSpeeds(a, b){
    if a is faster than b then
        return a
    else
        return b
}

function findFastestCar(){
    loop through all cars and return car with greatest speed
}

The OOP way would be create an object for car, maybe convert compareCarSpeeds into a prototype.

While the array way would be to create a 2D array, where one dimension is for the list of cars, and the second is for the set of data inside each car.

Alter
  • 3,332
  • 4
  • 31
  • 56
  • 1
    When reading through your code which would be easier to understand: and know what the variable contains `cars[0].max_speed` or `cars[0][2]`. Actually arrays are objects, everything in js is basically an object – Patrick Evans Oct 03 '14 at 19:49
  • So I can't escape using an object no matter what I do? Then I guess there really is no difference – Alter Oct 03 '14 at 19:53
  • I thought this was correct. Because you can define an object `var obj = {first:"value"};` and do `obj["first"];` – giannis christofakis Oct 03 '14 at 19:55
  • 1
    @giannischristofakis you can also do `[].foo = "bar"`, and... `"foo".bar = "baz"` (however, neither of those two examples are recommended.) – Kevin B Oct 03 '14 at 19:56
  • Pretty much comes down to preference and readability. See also: http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript – Moob Oct 03 '14 at 19:57
  • 3
    My general recommendation: Arrays should be used for uniform data, or if the order is important. Objects should be used for heterogeneous data. – Barmar Oct 03 '14 at 19:57
  • But in the end, this just comes down to style preference. As such, it's off-topic for SO, since it's primarily opinion-based. – Barmar Oct 03 '14 at 19:58
  • Thanks @KevinB those two were very good examples. So in my example, it's just another way to access properties or what? – giannis christofakis Oct 03 '14 at 20:00
  • Correct. bracket notation allows you to access the property (or create a property) using a string, which can be used this way: `var c = {}, a = "b"; c[a] = "d"; // c.b === "d"` thus allowing you to define or access a property using a stored string. It also allows you to use property names that would otherwise be invalid: `var a = {}; a["hello world!"] = "worky";` – Kevin B Oct 03 '14 at 20:04

0 Answers0