iEntry 10th Anniversary CSS Snippets JavaScript Snippets

 
 





Create an array in JavaScript

Arrays are very useful to store information that is similar. An example where an array is very useful is when storing the name of employees in one department in a company. There are many ways to create arrays in JavaScript. Below are some examples on how to create an array, all of them are the exact same array to your browser.

Example 1:
	<script>
	        students = new Array("Jay", "Dave", "Mathew", "Rodney", "Chad", "Derald");
	</script>
        
Example 2:
	<script>
	        students = new Array(6);
	        students[0] = "Jay"
	        students[1] = "Dave"
	        students[2] = "Mathew"
	        students[3] = "Rodney"
	        students[4] = "Chad"
	        students[5] = "Derald"
	</script>
        
Example 3:
	<script>
	        students = ["Jay", "Dave", "Mathew", "Rodney", "Chad", "Derald"];
	</script>
        

You maybe wonder why do we start at 0 in the Example 2. Well in JavaScript, like many other programming languages, when counting you start at 0 instead of a 1.
To print the value of a key in the array, you will simply use the key number in the array. In this case if we wanted to display Chad's name we would use students[4].