Asked  7 Months ago    Answers:  5   Viewed   37 times

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

and

var myObject = {'A': 'Athens', 'B':'Berlin'};

because they both behave the same, and also typeof(myArray) == typeof(myObjects) (both yield 'object').

Is there any difference between these variants?

 Answers

69

Virtually everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. This should be considered harmful though. Arrays are for numerically indexed data - for non-numeric keys, use an Object.

Here's a more concrete example why non-numeric keys don't "fit" an Array:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

alert(myArray.length);

This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.

Tuesday, June 1, 2021
 
Dunc
answered 7 Months ago
46

Objects

There is no benefit to using new Object(); - whereas {}; can make your code more compact, and more readable.

For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:

var myObject = {
        title:  'Frog',
        url:    '/img/picture.jpg',
        width:  300,
        height: 200
      };

Arrays

For arrays, there's similarly almost no benefit to ever using new Array(); over []; - with one minor exception:

var emptyArray = new Array(100);

creates a 100 item long array with all slots containing undefined - which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').

My recommendation

  1. Never use new Object(); - it's clunkier than {}; and looks silly.
  2. Always use []; - except when you need to quickly create an "empty" array with a predefined length.
Wednesday, June 2, 2021
 
Chvanikoff
answered 7 Months ago
51

Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.

If you are looping code with for..in your code may break because you will now be enumerating through these newly attached properties.

I suggest using something like jQuery's .data which keeps metadata attached to objects. If you don't want to use a library, re-implement jQuery.data

Tuesday, July 13, 2021
 
conmen
answered 5 Months ago
45

Property names are always strings or symbols.

If you pass something which isn't a string or symbol, it gets converted to a string.

The default toString() method on an array is roughly:

String.prototype.toString = function () { return this.join(","); }

So ['a'] gets converted to 'a'.

As a side note this only works with an array of length 1.

It works fine with arrays that are longer. You just need a matching value:

const o = {
    "a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);

And since any object can be converted to a string, and you can customise the toString method, you can do really weird things:

const data = {
  "42": "Hello"
}

class Weird {
    constructor(x) {
        this.x = x;
    }
    toString() {
        return this.x + 40;
    }
}

const w = new Weird(2);
console.log(data[w]);

(Note that doing really weird things is usually a stupid idea that makes it hard to debug your own code two weeks later).

Friday, August 6, 2021
 
Igor Tupitsyn
answered 4 Months ago
55

As order of values in array returned by Object.values() isn't guaranteed, you should consider use of .map() with some Object Destructuring. You can then extract object properties in separate variables and return them in desired order explicitly.

const data = [
  { amount: '100', user: 'admin', date: 'March 6, 2019' },
  { amount: '120', user: 'admin', date: 'March 6, 2019' },
  { amount: '80',  user: 'admin', date: 'March 7, 2019' },
  { amount: '200', user: 'admin', date: 'March 7, 2019' }
];

const result = data.map(({ amount, user, date }) => [amount, user, date]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sunday, August 8, 2021
 
mpen
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share