[ACCEPTED]-Why can I add named properties to an array as if it were an object?-javascript-objects

Accepted answer
Score: 135

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

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

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


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

Score: 14

In JS arrays are objects, just slightly 2 modified (with a few more functions).

Functions 1 like:

Score: 5

Everything in JavaScript is an object besides 7 primitive types.

The code

var myArray = Array();

creates an instance 6 of the Array object while

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

creates an instance 5 of Object object.

Try the following code


So 4 you will see the difference is in the type 3 of object constructor.

The instance of the 2 Array object will contain all the properties 1 and methods of the Array prototype.

Score: 5

Me thinks, me too metaphorical and cryptic 54 with previous answer. Clarification follows.

An 53 instance of Array, Boolean, Date, Function, Number, RegExp, String 52 is an Object but enhanced with methods and 51 properties specific to each type. For example, an 50 array has a predefined length property while generic 49 objects do not.




Intrinsically, the 48 FF Gecko interpreter also distinguishes 47 between Arrays and generic Objects with 46 distinct differences evaluating language 45 constructs.

  ra=[  "one",   "two",   "three"]; ra.a=4;
  ob={0:"one", 1:"two", 2:"three"}; ob.a=4;
    ra            +"\n\n"+
    ob            +"\n\n"+
    ra.toSource() +"\n\n"+
    ra.a          +"\t .toSource() forgot me! \n\n"+
    ra.length     +"\t and my length! \n\n"+
  ps=""; for(i in ra)ps+=i+" "; alert(ps);  /* NB .length is missing! */
  ps=""; for(i in ob)ps+=i+" "; alert(ps);



[object Object]

["one", "two", "three"]

4    .toSource() forgot me! 

3    and my length! 

({0:"one", 1:"two", 2:"three", a:4})

and 0 1 2 a and 0 1 2 a.

Regarding 44 the statement that all objects are functions:

It 43 is neither syntactically nor semantically 42 correct to use an arbitrary object instance 41 as a function like 123() or "abc"() or []() or {}() or obj() where 40 obj is any type other than Function, so an arbitrary 39 object INSTANCE is not a Function. However, given 38 an object obj and it's type as Array, Boolean, Date, ..., how did obj come 37 to be as an Array, Boolean, Date, ...? What is an Array, Boolean, Date, ...?

    alert([Array, Boolean, Date, Function, 
              Number, Object, RegExp, String] . join('\n\n') );


function Array() {
    [native code]

function Boolean() {
    [native code]

function Date() {
    [native code]

function Function() {
    [native code]

function Number() {
    [native code]

function Object() {
    [native code]

function RegExp() {
    [native code]

function String() {
    [native code]

In every 36 case, without equivocation, the object type 35 manifests as a function definition, hence the statement 34 that all objects are functions! (The tongue-in-cheek 33 is that I intentionally obscured and blurred 32 the distinction of an object instance with 31 that of it's type! Still, this shows "you 30 can't have one without the other", Object 29 and Function! Capitalization emphasizes 28 type as opposed to instance.)

Both a functional 27 and object paradigm seem to be fundamental 26 to the programming and implementing of the 25 JS interpreter low level built-in primitives, such 24 as Math and JSON and true.

 javascript:alert([Math, JSON, true.toSource()].join("\n\n"));


[object Math]

[object JSON]

(new Boolean(true))

At the time of the 23 development of Javascript, an object-centric 22 programming style (OOP's - Object Oriented 21 Programming style - the "'s" is my own pun!) was 20 in vogue and the interpreter was similarly 19 christened with Java to give it greater 18 credibility. Functional programming techniques 17 were relegated to more abstract and esoteric 16 examinations studying the theories of Automata, Recursive 15 Functions, Formal Languages, etc. and as 14 such not as palatable. However, the strengths 13 of these formal considerations are clearly 12 manifest in Javascript particularly as implemented 11 in FF's Gecko engine (ie. .toSource()).

The Object definition 10 for Function is particularly satisfying 9 for it is defined as a recurrence relation! defined 8 using it's own definition!

function Function() { [native code] }
and since a function 7 is an Object the same sentiment holds for
function Object() { [native code] }.

Most 6 of the other definitions quiesce to a static 5 terminal value. However, eval() is a particularly 4 powerful primitive and so a String can also 3 embed arbitrary functionality.

Note again, the 2 vernacular used above obscures object type 1 and instance distinction.

Score: 4

You can add named properties to almost anything 10 in javascript but that doesn't mean that 9 you should. Array in javascript should be used 8 as a list, if you want an associative array 7 use Object instead.

Beware that if you really want 6 to use an Array with named properties instead 5 of Object those properties won't be accessible 4 in a for...of loop and you might also get unexpected 3 results when JSON encoding it to pass it 2 around. See example below where all non-numeric indexes 1 get ignored:

let arr = [];
let obj = {};

arr['name'] = 'John';
obj['name'] = 'John';

console.log(arr);    // will output [name: "John"]
console.log(obj);    // will output {name: "John"}

JSON.stringify(arr); // will return [] <- not what you expected
JSON.stringify(obj); // will return {"name":"John"}
Score: 2

The difference between the arrays and the 8 other objects in JavaScript. While arrays 7 have a magically updating length property, for 6 objects other than the arrays there is no 5 way to implement such a property.

var arrName = [];
arrName[5] = "test";
arrName.length; // <- 6

Array are 4 used to store things with an ordinal index 3 - use it like a traditional array, stack, or 2 queue. An object is a hash - use it for 1 data that has a distinct key.

Score: 1

In JavaScript Arrays are special typed objects

typeof new Array(); // returns "object" 
typeof new Object(); // returns "object

Arrays 4 used numbered Indexes and Objects used named 3 Indexes

so we can able add named properties 2 to Array

const arr = []
arr["A"] = "Hello" //["A":"Hello"]

console.log(arr.length) // 0 

arr.length returns 0 , because array 1 with named indexes are prefer to call Objects

console.log(Object.keys(clothing)); // ["A"]
console.log(Object.keys(clothing).length); //1

More Related questions