Are Javascript arrays primitives? Strings? Objects?

Are arrays merely objects in disguise? Why/why not? In what way(s) are they (such/not)?

I have always thought of arrays and objects in JS as essentially the same, primarily because accessing them is identical.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var obj = {'I': 'me'};
var arr = new Array();
arr['you'] = 'them';
console.log(obj.I);
console.log(arr.you);
console.log(obj['I']);
console.log(arr['you']);
</code>
<code>var obj = {'I': 'me'}; var arr = new Array(); arr['you'] = 'them'; console.log(obj.I); console.log(arr.you); console.log(obj['I']); console.log(arr['you']); </code>
var obj = {'I': 'me'};
var arr = new Array();
arr['you'] = 'them';

console.log(obj.I);
console.log(arr.you);
console.log(obj['I']);
console.log(arr['you']);

Am I mislead/mistaken/wrong? What do I need to know about JS literals, primitives, and strings/objects/arrays/etc…?

Are arrays/objects merely strings in disguise? Why/why not? In what way(s) are they (such/not)?

8

Arrays are objects.

However, unlike regular objects, arrays have certain special features.

  1. Arrays have an additional object in their prototype chain – namely Array.prototype. This object contains so-called Array methods which can be called on array instances. (List of methods is here: http://es5.github.io/#x15.4.4)

  2. Arrays have a length property (which is live, ergo, it auto-updates) (Read here: http://es5.github.io/#x15.4.5.2)

  3. Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.io/#x15.4.5.1). If you set a new property to an array and that property’s name is a sting which can be coerced to an integer number (like '1', '2', '3', etc.) then the special algorithm applies (it is defined on p. 123 in the spec)

Other than these 3 things, arrays are just like regular objects.

Read about arrays in the spec: http://es5.github.io/#x15.4

20

Objects are an unordered map from string keys to values, arrays are an ordered list of values (with integer keys). That’s the main difference. They’re both non-primitive, as they’re composed of multiple values, which also implies pass-by-reference in JavaScript.

Arrays are also a kind of object, though, so you can attach extra properties to them, access their prototype and so on.

In your revised example, you’re only taking advantage of the fact that an array is actually an object, i.e. you can set any property on them. You shouldn’t do that. If you don’t need an ordered list of values, use a plain object.

13

Strings can be either primitive or objects, depending on how they were declared.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var str = 'yes';
</code>
<code>var str = 'yes'; </code>
var str = 'yes';

Gives you a primitive, while,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var str = new String('yes');
</code>
<code>var str = new String('yes'); </code>
var str = new String('yes');

will give you a String object.


All arrays are the same (Whether or not they were defined with [] or new Array()), are of the type object and inherit from the “Array” object’s prototype. There aren’t real classes in Javascript, everything is an object, and there’s a system defined object called Array. It has a property called ‘prototype’ (of type object), and when you use the new keyword on an object with a prototype property, it creates an instance with a reference to the contents of the prototype and stores it in your variable. So all arrays you’ve ever used in Javascript are objects and instances of Array’s prototype property.

In any case, although arrays really are objects, they behave like arrays because of their useful properties and functions (Such as length, slice, push etc).

Another note, although I said there are no classes, when you do this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>console.log(Object.prototype.toString.call(your_object));
</code>
<code>console.log(Object.prototype.toString.call(your_object)); </code>
console.log(Object.prototype.toString.call(your_object));

it will give you a string in the form [object Object]. But what’s useful is that when you call it with an array, you get [object Array] same with functions which give [object Function] and a number of other system defined types, which assists in differentiating between normal objects and arrays (Since the typeof operator will always just return the string ‘object’).

Try this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var a = Array;
</code>
<code>var a = Array; </code>
var a = Array;

and go into firebug and examine the contents of a, especially it’s ‘prototype’ property.

Edit: Changed the wording a bit, to be more correct. In fact when you use the new keyword, it creates an instance which references the prototype object. So any changes made to the prototype after the instance’s declaration, will still affect the instance.

Edit: In answer to your latest revised question (are arrays/objects actually strings in disguise): No. They are objects, as I’ve explained. Strings are either a primitive type, or an object type (An instance of the String object) which contains the primitive equivalent as one of it’s properties.

21

Arrays are not primitives in Javascript, they are objects. The key difference is that as a result, when you pass an array to a function it is passed by reference, not by value.

So yes! Arrays are objects in javascript, with a full blown Array.prototype and everything (don’t touch that though…)

The confusion comes from the fact that javascripts lets you access object attributes in two ways:

myObj.attribute
or
myObj[“attribute”]

Really what makes an array an array has nothing to do with the way you store data — any object can store values using the syntax you use to store the array — what makes an array an array is the fact that array methods (e.g. shift() and sort()) are defined for Array.prototype.

4

Trying to be brief with what I believe to be of the most significance: arrays have a number of methods that objects do not. Including:

  • length
  • push
  • pop

An object declared as var x = {foo:bar} has no access to a .length() method. They are both objects but with the array as a sort of superset with methods mentioned as above.

I don’t feel I this is even close to being of Crockford standard in terms of explanation but I’m trying to be succinct.

If you want to get some quick results, open up Firebug or your javascript Console and try Array.prototype and Object.prototype to see some details

Update: In your example you declare an array and then do:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>foo['bar'] = 'unexpectedbehaviour';
</code>
<code>foo['bar'] = 'unexpectedbehaviour'; </code>
foo['bar'] = 'unexpectedbehaviour';

will produce unexpected results and won’t be available in simple loops such as:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var foo=[0,1];
foo['bar'] = 2;
for(var i=0;i<foo.length;i++){
console.log(foo[i]);
}
//outputs:
//0
//1
</code>
<code>var foo=[0,1]; foo['bar'] = 2; for(var i=0;i<foo.length;i++){ console.log(foo[i]); } //outputs: //0 //1 </code>
var foo=[0,1];
foo['bar'] = 2;

for(var i=0;i<foo.length;i++){
    console.log(foo[i]);
}

//outputs: 
//0
//1

An array can accept foo['bar']=x or foo.bar=y like an object but won’t necessarily be available to be looped through as highlighted above.

Not that I’m saying that you can’t iterate through the properties of an object, just that when working with an Array, you’re utilising that unique functionality and should remember not to get confused.

7

In JavaScript you have a few types, everything else is an object. The types in JavaScript are: boolean, number, and string. There are also two special values, “null” and “undefined”.

So the quest “is a JavaScript array an object?” is slightly ambiguous. Yes, a JavaScript array is an “object” but it is not an instance of “Object”. A JavaScript array is an instance of “Array”. Although, all objects inherit from Object; you can view the inheritance chain on the MDC. Additionally, arrays have slightly different properties than an object. Arrays have the .length property. They also have the .slice(), .join(), etc methods.

Douglas Crockford provides a nice survey of the language’s features. His survey discusses the differences you are asking about. Additionally, you can read more about the difference between literals and constructors in question #4559207.

6

Arrays are Objects, but of a specialized nature. Objects are collections of values indexed by keys (in Javascript notation, {'key': 'value'}), whereas Arrays are Objects whose keys are numeric (with a few functions and properties). The key difference between them is obvious when you use a for each loop–an Object will iterate over all the values in its properties, whereas an Array will return the keys instead. Here’s a link to a JSFiddle demonstrating the difference–notice that the first for each, which uses an array, returns the indexes, not the values; in contrast, the second for each returns the actual values at those keys.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật