What is an array in Javascript?
Topics

--><!-- Nothing works without HTML -->








<div>
<h1>Arrays in Javascript - difference between arrays and objects</h1>
<h6>CLICK the button below (sneak peek) to peek at the code.</h6>
<p>

According to the <a href="http://www.merriam-webster.com/dictionary/array" target="_blank">Webster dictionary</a>
"to array" is to sort out things in an orderly way. So in computer science it comes to mean (as a noun) an ordered row of data,
or as it is also called, a field. So an array is nothing but a set of data that has been sorted.
You can go about declaring an array in different ways. First the easy and clear way:

</p>




<script type="text/javascript">

var someData = new Array(); //an array is an object

someData [0] = "Charles";
someData [1] = "Spencer";
someData [2] = "Chaplin";
someData [3] = "was one of the greatest artists of all time.";

alert (someData [0]+ " " + someData [1]+ " " + someData [2]+ " " + someData [3]);


</script>


<p>So here you have got an array of 4 (!) elements. One of the mistakes made most often, is to forget
that an array starts with "0". I advise you to keep this in mind.</p>

<p>You can also declare it this way, seeing that an array actually starts with zero:</p>

<script type="text/javascript">
someData = null; //destroy this

var someData = new Array("Charles", "Spencer", "Chaplin", "was one of the greatest artists of all time.");
alert (someData [0]+ " " + someData [1]+ " " + someData [2]+ " " + someData [3]);
</script>


<p>Or the very short form, which makes it very clear to see it as an object:</p>

<script type="text/javascript">
someData = null; //destroy this

var someData = ["Charles", "Spencer", "Chaplin", "was one of the greatest artists of all time."];

alert (someData [0]+ " " + someData [1]+ " " + someData [2]+ " " + someData [3]);

</script>


<p>In some ways this is like an array:</p>


<script type="text/javascript">
var person = {
0:"Charles",
1:"Spencer",
2:"Chaplin",
3:"was one of the greatest artists of all time."
};
</script>

<pre>

var person = {
0:"Charles",
1:"Spencer",
2:"Chaplin",
3:"was one of the greatest artists of all time."
};

</pre>
<p>But see, whereas an array inherits from object, its prototype is "array", which has got quite a few extras:</p>
<img src="images_July_2015/array.png" width="391" height="670" alt="an array is an object as can be seen from the prototype" />



<p>This is the object without the extras, so we can't say that object and array are equivalent and we can see
that an array has got properties and methods that it inherits from object, but an object is not an array because it has only
got the properties and methods of object:</p>

<img src="images_July_2015/object.png" width="382" height="347" alt="difference between array and object, an arry is not an object but inherits from object" />


















<?php $Weblog->share ();?>



<br/>
<br/>
<br/>

</div>

Sneak peek of the server side code