This section provides a quick description of similarities and differences of 'Array' and 'Object'. A tutorial example is provided on how to compare an 'Array' object to an 'Object' object.
JavaScript supports a number of predefined core object types.
Among them, "Object" and "Array" have very close relations.
If you compare "Array" with "Object", you should see the following similarities and differences:
"Array" is subclass, or sub-prototype, of "Object". So "Array" inherits all features from "Object".
"Array" is not a new data type. "Array" and "Object" are sharing the same data type "object".
The "typeof" operator on an "Array" object returns "object".
The "instanceof" operator on an "Array" object matches "Array". It also matches "Object",
because "Array" is a subclass of "Object".
An object of "Object" can have indexed properties using the same syntax as "Array" objects.
An object of "Object" is not an object of "Array".
An object of "Array" is also an object of "Object".
Here is a JavaScript tutorial example that shows how "Array" and "Object" are similar to each other:
<html>
<!-- Object_and_Array.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Comparing Object and Array</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Creating an object of "Array" - array literal
var bookArray = [
"JavaScript Tutorial",
"Herong Yang",
2008,
"Programming"
];
// Creating an object of "Object" - object literal
var bookObject = {
title: "JavaScript Tutorial",
author: "Herong Yang",
year: 2008,
category: "Programming"
};
// Checking "bookArray"
document.writeln();
document.writeln("About the \"Array\" object:");
document.writeln(" Type: "+(typeof bookArray));
document.writeln(" Instance Of Object: "
+(bookArray instanceof Object));
document.writeln(" Instance Of Array: "
+(bookArray instanceof Array));
document.writeln(" Members:");
for (var item in bookArray) {
document.writeln(" "+item+": "+bookArray[item]);
}
// Checking "bookObject"
document.writeln();
document.writeln("About the \"Object\" object:");
document.writeln(" Type: "+(typeof bookObject));
document.writeln(" Instance Of Object: "
+(bookObject instanceof Object));
document.writeln(" Instance Of Array: "
+(bookObject instanceof Array));
document.writeln(" Members:");
for (var item in bookObject) {
document.writeln(" "+item+": "+bookObject[item]);
}
</script>
</pre>
</body>
</html>
The output of this tutorial example shows that how an "Array" object is similar to an "Object" object:
About the "Array" object:
Type: object
Instance Of Object: true
Instance Of Array: true
Members:
0: JavaScript Tutorial
1: Herong Yang
2: 2008
3: Programming
About the "Object" object:
Type: object
Instance Of Object: true
Instance Of Array: false
Members:
title: JavaScript Tutorial
author: Herong Yang
year: 2008
category: Programming