Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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)?

like image 363
Jared Farrish Avatar asked Feb 19 '11 02:02

Jared Farrish


People also ask

Are JavaScript arrays primitive?

Numbers, boolean values, and the null and undefined types are primitive. Objects, arrays, and functions are reference types. A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit.

Are arrays in JavaScript considered objects?

Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

Is primitive array an object?

No, arrays are not primitive datatypes in Java. They are container objects which are created dynamically. All methods of class Object may be invoked on an array. They were considered as reference data types.

Is string an object or primitive in JavaScript?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string.


1 Answers

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.com/#x15.4.4)

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

  3. Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.com/#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.com/#x15.4

like image 154
Šime Vidas Avatar answered Sep 28 '22 00:09

Šime Vidas