-1

Could someone explain this block of code to me and what the type of 'arr' is. I know that an array is an object but

  1. Why does the [[Class]] show up as Array if it behaves like an Object
  2. arr.length returns 3. How?

    var arr = [0, 1, 3];
    arr.name = "asdf";
    
    console.log(arr[1] + " " + arr.name + " " + arr.length); 
    // Returns-> 1 asdf 3
    
    Object.prototype.toString.call(arr); 
    // Returns-> "[object Array]"
    

Whats the deal here?


This has already been answered in good detail in this SO post

Are Javascript arrays primitives? Strings? Objects?

Community
  • 1
  • 1
var x
  • 135
  • 6
  • `Object.prototype.toString.call([]);` will always give `"[object Array]"`, there's nothing special about appending a property to it. The length is 3 because you added 3 elements (`0, 1, 3`). – jbabey Jan 16 '13 at 16:51

4 Answers4

0

var arr = [0, 1, 3] is just syntactic sugar for var arr = Array.new(0, 1, 3). It's the same thing, and therefore arr is an Array, and an instance of Array is an object:

var arr = [0, 1, 3];
typeof arr;  // returns "object"
arr instanceof Array;  // returns true

Array overrides the lenght() function to only count the number of elements in the array; when you set arr. name = "asdf", you are setting a property to this specific object, but it is not counted by the length() function.

Jorge Gajon
  • 1,759
  • 10
  • 10
0

JavaScript arrays are specialized objects, so they are both arrays and objects. So you can add properties to them like any other object. Only numeric properties are taken into account for the length property so adding arbitrary properties like name will not affect it.

Musa
  • 96,336
  • 17
  • 118
  • 137
0

All javascript variables are objects. Some objects like this one are also arrays.

So you can set properties (since it is an object) and also look at properties specific to an array (since it is an array).

argentage
  • 2,758
  • 1
  • 19
  • 28
0

For 1, see section 15.4.5 "Properties of Array Instances":

Array instances inherit properties from the Array prototype object and their [[Class]] internal property value is "Array". Array instances also have the following properties.

For 2, see section 15.4.5.2 "length"

The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.

Paul Butcher
  • 6,902
  • 28
  • 39