3

I recently came across some code which I am a little confused about. Below is similar code, have a look:

var x = [];
console.log(x); // prints [] (no surprise)
x[0] = "abc";
console.log(x); // prints ["abc"] (no surprise)
x["test"] = "testing"
console.log(x); // prints ["abc"] 
console.log(x.test); // prints "testing"

so in this case.. the same variable, x, is both array and an object. How is this possible? If it acts as both, then console.log(x) should print something like ["abc",test:"testing"] but that syntax is wrong.

So whats happening in this case?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
raj
  • 694
  • 1
  • 5
  • 22

1 Answers1

4

All Arrays are Objects, (not only them, everything in JavaScript is an Object (except the primitives though))

console.log([] instanceof Object);
// true

just that they are special kind of objects which process integer keys differently.

So, you can expect them to act like normal JavaScript Objects. You can add arbitrary properties to them.

About the console.log result,

[ 'abc', test: 'testing' ]

is just a representation given by the implementation. If the representation has a key : value format, then it is a normal property associated with that array. That's all.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 2
    *"everything in JavaScript is an Object"* Well...except the things that aren't, like primitives. But *most* things in JavaScript are objects, indeed. – T.J. Crowder Jan 30 '16 at 11:33
  • "just that they are special kind of objects which process integer keys differently". can you elaborate on that? .. if i understand correctly an array is something like `{1 : value1,2 : value2}` etc? but is displayed [value1,value2] is that it ? – raj Jan 30 '16 at 11:38
  • @raj Arrays are ordered collection of data. So, you don't have to explicitly show the index corresponding to each of the elements. That is why the representations normally omit that. – thefourtheye Jan 30 '16 at 11:40
  • To be a bit more precise, "everything in Javascript is or can be promoted to an Object". Example : `(1).toFixed(3) === "1.000"` , so here `1` was considered as `new Number(1)` – GameAlchemist Jan 30 '16 at 17:30