They say that everything in the world of javascript is considered to be an object. I decided to test this theory by running the code below, but the outcome was not what I expected.
var color = [];
console.log(color.constructor === Array);
color[color['purple'] = 2] = 'green';
console.log(color);
console.log(color.constructor === Array);
console.log(Array.isArray(color));
Based on what I knew, arrays are designed to only store values with numerical keys. If I were to assign a string as a key, it would make more sense to utilize objects instead. However, here's what happened when I executed the code:
true
[ <2 empty items>, 'green', purple: 2 ]
true
true
When I check typeof color
, it returns object
, which is a common output for all arrays. But how does the element purple: 2
end up inside the color
variable? Shouldn't color
be classified as an object rather than an array? Is there a built-in method that can differentiate between an array and an object?
Similar questions have been raised before, however, the circumstances varied slightly from this specific case. I tried searching for answers related to this scenario without much success.