2

A colleague, by mistake wrote this code:

var parameters = [];
// some lengthy code here
parameters.firstParameter = "first parameter value";
parameters.secondParameter = "second parameter value";

He had declared parameters variable as an array, but somewhere else he had used it as an object, adding parameters to it.

The results of testing the type of this parameter is as follow (in Google Chrome's console):

parameters;
// prints []

typeof parameters;
// prints "object"

parameters instanceof Array;
// prints true

So, is it an object or an array at last? Or does it have a dual nature, both array and object at the same time?

Hamid Barani
  • 191
  • 1
  • 1
  • 8
  • 8
    In JavaScript pretty much *everything* is an object, and can have properties; hence `[object Array]`, `[object Object]`... – David Thomas Apr 30 '14 at 11:27
  • @DavidThomas And every object is also an array, in a manner of speaking (you can address its elements using an indexer). More importantly, why do you care? What observable difference between the two are you expecting? – Luaan Apr 30 '14 at 11:27
  • @Luaan: true of course, I never thought to add that though. :) – David Thomas Apr 30 '14 at 11:28

1 Answers1

-1

In JavaScript everything is an Object. If you define an Array so it'll be treat as an object in JavaScript. Since it is an object, you can access properties associated to it.

Geeky Ninja
  • 6,002
  • 8
  • 41
  • 54
  • 2
    Any reference for that claim that *everything* is an object? – Saeed Neamati Apr 30 '14 at 11:31
  • 1
    Well, not [**everything**](http://www.2ality.com/2011/03/javascript-values-not-everything-is.html) is an object. Among other things `null` is not. – leo Apr 30 '14 at 11:34
  • And none of the primitives are objects. (Common misconception, because JS automatically turns them into objects as soon as you try to use them as objects.) – JJJ Apr 30 '14 at 11:35
  • And in modern browsers, more limitations are appearing all the time. For example, in Chrome, `var pom = 23; pom.myTest = "Hi"; alert(pom.myTest);` will give `undefined`. – Luaan Apr 30 '14 at 11:35
  • In JS objects are bit different from what we see in languages likes C#, C++ or Java. An object in JS is simply a hashmap with key-value pairs. A key is always a string, and a value can be anything including strings, integers, booleans, functions, other objects etc – Geeky Ninja Apr 30 '14 at 11:55