maze star
maze star

Reputation: 29

Javascript - how are array stored internally?

In the fiddle - http://jsfiddle.net/vwwkf18c/ or below code snippet -

var a = [3, 4];
var b = [6, 2];
var c = $.extend({}, a, b);
alert(c[1]); //alerts 2
alert(a); //alerts array a contents
alert(c); //does not return contents of c

My questions - 1) After what has been alerted, we can infer that "c" is an object but not an array object. Please confirm. 2) Secondly it is said that internal representation of an array is an object literal, is that right? Which means that array "a" would be stored as given below -

var a = {
0: 3,
1: 4
}

Is it right? 3) How is a or b stored internally and how is it different from the internal representation of "c"?

Upvotes: 2

Views: 522

Answers (2)

Vikram
Vikram

Reputation: 73

  1. Yes, c is an object, but not an array.
  2. The internal representation of a (which is an array) has a property called 'length' in addition to '0' and '1'
  3. c has the properties of '0' and '1', but not the property 'length'

Check out this jsfiddle

var a = [3, 4];

var b = [6, 2];

var c = $.extend({}, a, b);

alert(c[1]); //alerts 2
alert(a); //alerts array a contents
alert(Object.getOwnPropertyNames(c)); //does not return contents of c
alert(Object.getOwnPropertyNames(a));

Hope that is helpful

Vikram

Upvotes: 0

Quentin
Quentin

Reputation: 944201

  1. See the docs: "Returns: Object"
  2. No. An object literal is a piece of JavaScript syntax for creating objects with. Arrays are an object type that inherits (along the prototype chain) from basic Objects. The Array type has a different toString method than the basic Object, which is why alert gives different results.
  3. That is implementation specific (and also of no importance to anyone writing JavaScript rather than a JavaScript runtime)

Upvotes: 1

Related Questions