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

asked Jan 16, 2013 at 16:48
1
  • 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). Commented Jan 16, 2013 at 16:51

4 Answers 4

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.

answered Jan 16, 2013 at 16:50
Sign up to request clarification or add additional context in comments.

Comments

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

answered Jan 16, 2013 at 16:51

Comments

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.

answered Jan 16, 2013 at 16:54

Comments

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.

answered Jan 16, 2013 at 16:50

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.