Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array and object in single variable? [duplicate]

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?

like image 712
raj Avatar asked Jun 07 '26 18:06

raj


1 Answers

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.

like image 195
thefourtheye Avatar answered Jun 10 '26 06:06

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!