Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1099445 of Arrays

  • Revision slug: Learn/JavaScript/First_steps/Arrays
  • Revision title: Arrays
  • Revision id: 1099445
  • Created:
  • Creator: BenCrab
  • Is current revision? No
  • Comment

Revision Content

{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/TBD", "Learn/JavaScript/First_steps")}}

{{IncludeSubnav("/en-US/Learn")}}

In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective: To understand what arrays are and how to manipulate them in JavaScript.

What is an Array?

Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.

If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would be bad enough, but what about 100 items, or 1000? We'll return to this example later on in the article.

As in previous articles, let's learn about the real basics of arrays by entering some examples into a JavaScript console. We've provided one below (you can also open this console in a separate tab or window, or use the browser developer console if you'd prefer).

{{ EmbedLiveSample('Hidden_code', '100%', 300) }}

Creating an array

Arrays are constructed of square brackets, which contain a list of items separated by commas.

  1. Let's say we wanted to store a shopping list in an array — we'd do something like the following. Enter the following lines into your console:
    var shopping = ['bread', 'milk', 'cheese', 'hummous', 'noodles'];
    shopping;
  2. In this case, each item in the array is a string, but bear in mind that you can store any item in an array — string, number, object, another variable, even another array. You can also mix and match item types — they don't all have to be numbers, strings, etc. Try these:
    var sequence = [1, 1, 2, 3, 5, 8, 13];
    var random = ['tree', 795, [0, 1, 2]];
  3. Try creating a couple of arrays of your own, before you move on.

Accessing and modifying array items

You can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string.

  1. Enter the following into your console:
    shopping[0];
    // returns "bread"
  2. You can also modify an item in an array by simply giving a single array item a new value. Try this:
    shopping[0] = 'tahini';
    shopping;
    // shopping will now return [ "tahini", "milk", "cheese", "hummous", "noodles" ]
    Note: We've said it before, but just as a reminder — computers start counting from 0!
  3. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:
    random[2][2];
  4. Try further playing with, and making some more modifications to, your array examples before moving on.

Finding the length of an array

You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the {{jsxref("Array.prototype.length","length")}} property. Try the following:

sequence.length;
// should return 7

This has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. So for example:

var sequence = [1, 1, 2, 3, 5, 8, 13];
for(var i = 0; i < sequence.length; i++) {
  console.log(sequence[i]);
}

You'll learn about loops properly in a future article, but briefly, this code is saying:

  1. Start looping at item number 0 in the array.
  2. Stop looping at the item number equal to the length of the array. This will work for an array of any length, but in this case it will stop looping at item number 7 (this is good, as the last item — which we want the loop to cover — is 6.
  3. For each item, print it out to the browser console with console.log().

Some useful array methods

In this section we'll look at some rather useful array-related methods that allow us to split strings into array items and vice versa, and add new items into arrays.

Converting between strings and arrays

Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the {{jsxref("String.prototype.split()","split()")}} method. In it's simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings inbetween the separator as items in an array.

Note: OK, this is technically a string method, not an array method, but I've put it in with arrays as it goes well here.

  1. Let's play with this, to see how it works. First, create a string in your console:
    var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
  2. Now let's split it at each comma:
    var myArray = myData.split(',');
    myArray;
  3. Finally, try finding the length of your new array, and retrieving some items from it:
    myArray.length;
    myArray[0]; // the first item in the array
    myArray[1]; // the second item in the array
    myArray[myArray.length-1]; // the last item in the array
  4. You can also go the opposite way using the {{jsxref("Array.prototype.join()","join()")}} method. Try the following:
    var myNewString = myArray.join(';');
    myNewString;

Adding and removing array items

We've not yet covered adding and removing array items — lets look at this now. We'll use the myArray array we ended up with in the last section. If you've not already followed that section, create the array first in your console:

var myArray = [ "Manchester", "London", "Liverpool", "Birmingham", "Leeds", "Carlisle" ];

First of all, to add or remove an item at the end of an array we can use {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} respectively.

  1. Let's use push() first — note that you need to include one or more items that you want to add to the end of your array. Try this:
    myArray.push('Cardiff');
    myArray;
    myArray.push('Bradford', 'Brighton');
    myArray;
    
  2. The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
    var newLength = myArray.push("Bristol");
    myArray;
    newLength;
  3. Removing the last item from the array is as simple as running pop() on it. Try this:
    myArray.pop();
  4. The item that was removed is returned when the method call completes. You could also do this:
    var removedItem = myArray.pop();
    myArray;
    removedItem;

{{jsxref("Array.prototype.unshift()","unshift()")}} and {{jsxref("Array.prototype.shift()","shift()")}} work in exactly the same way, except that they work on the beginning of the array, not the end.

  1. First unshift() — try the following commands:
    myArray.unshift('Edinburgh');
    myArray;
  2. Now shift(); try these!
    var removedItem = myArray.shift();
    myArray;
    removedItem;

Active learning: Printing those products!

Let's return to the example we described earlier — printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers — Each of these marks a place where you have to add something to the code. They are as follows:

  1. Below the // number 1 comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called products.
  2. On the same line as the // number 2 comment is the beginning of a for loop. In this line we currently have i <= 0, which is a conditional test that causes the for loop to stop immediately, because it is saying "stop when i is no longer less than or equal to 0", and i starts at 0. We'd like you to replace this with a conditional test that stops the loop when i is no longer less than the product array's length.
  3. Just below the // number 3 comment we want you to write a line of code that splits the current array item (name:price) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the Useful string methods article for some help, or even better, look at the {{anch("Converting between strings and arrays")}} section of this article.
  4. As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the first strings article.
  5. There is a variable called total that is created and given a value of 0 at the top of the code. Inside the loop (below // number 4) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an assignment operator to do this.
  6. We want you to change the line just below // comment 5 so that the itemText variable is made equal to "current item name — $current item price", for example "Shoes — $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, so you should be OK with this.

{{ EmbedLiveSample('Playable_code', '100%', 600) }}

Active learning: Top 5 searches

A good use for array methods like {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.

In this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, The top 5 previous search terms are displayed in the list. When the number of terms gets to over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.

Note: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.

To complete the app, we need you to:

  1. Add a line below the // number 1 comment that adds the current value entered into the search input to the start of the array. This can be retrieved using searchInput.value.
  2. Add a line below the // number 2 comment that removes the value currently at the end of the array.

{{ EmbedLiveSample('Playable_code_2', '100%', 600) }}

Conclusion

After reading through this article we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops being used to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!

The only thing left to do is work through this module's assessment, which will test your understand of the articles that came before it.

See also

  • Indexed collections — an advanced level guide to arrays and their cousins, typed arrays.
  • {{jsxref("Array")}} — the Array object reference page — for a detailed reference guide to the features discussed in this page, and many more.

{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/TBD", "Learn/JavaScript/First_steps")}}

Revision Source

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/TBD", "Learn/JavaScript/First_steps")}}</p>

<div>{{IncludeSubnav("/en-US/Learn")}}</div>

<p class="summary">In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisites:</th>
   <td>Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.</td>
  </tr>
  <tr>
   <th scope="row">Objective:</th>
   <td>To understand what arrays are and how to manipulate them in JavaScript.</td>
  </tr>
 </tbody>
</table>

<h2 id="What_is_an_Array">What is an Array?</h2>

<p>Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.</p>

<p>If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would be bad enough, but what about 100 items, or 1000? We'll return to this example later on in the article.</p>

<p>As in previous articles, let's learn about the real basics of arrays by entering some examples into a JavaScript console. We've provided one below (you can also <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">open this console</a> in a separate tab or window, or use the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer console</a> if you'd prefer).</p>

<div class="hidden">
<h6 id="Hidden_code">Hidden code</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;JavaScript console&lt;/title&gt;
    &lt;style&gt;
      * {
        box-sizing: border-box;
      }

      html {
        background-color: #0C323D;
        color: #809089;
        font-family: monospace;
      }

      body {
        max-width: 700px;
      }

      p {
        margin: 0;
        width: 1%;
        padding: 0 1%;
        font-size: 16px;
        line-height: 1.5;
        float: left;
      }

      .input p {
        margin-right: 1%;
      }

      .output p {
        width: 100%;
      }

      .input input {
        width: 96%;
        float: left;
        border: none;
        font-size: 16px;
        line-height: 1.5;
        font-family: monospace;
        padding: 0;
        background: #0C323D;
        color: #809089;
      }

      div {
        clear: both;
      }

    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

    
  &lt;/body&gt;

  &lt;script&gt;
    var geval = eval;
    function createInput() {
      var inputDiv = document.createElement('div');
      var inputPara = document.createElement('p');
      var inputForm = document.createElement('input');

      inputDiv.setAttribute('class','input');
      inputPara.textContent = '&gt;';
      inputDiv.appendChild(inputPara);
      inputDiv.appendChild(inputForm);
      document.body.appendChild(inputDiv);

      inputForm.addEventListener('change', executeCode);
    }

    function executeCode(e) {
      try {
        var result = geval(e.target.value);
      } catch(e) {
        var result = 'error — ' + e.message;
      }

      var outputDiv = document.createElement('div');
      var outputPara = document.createElement('p');

      outputDiv.setAttribute('class','output');
      outputPara.textContent = 'Result: ' + result;
      outputDiv.appendChild(outputPara);
      document.body.appendChild(outputDiv);

      e.target.disabled = true;
      e.target.parentNode.style.opacity = '0.5';

      createInput()
    }
    
    createInput();

  &lt;/script&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code', '100%', 300) }}</p>

<h3 id="Creating_an_array">Creating an array</h3>

<p>Arrays are constructed of square brackets, which contain a list of items separated by commas.</p>

<ol>
 <li>Let's say we wanted to store a shopping list in an array — we'd do something like the following. Enter the following lines into your console:
  <pre class="brush: js">
var shopping = ['bread', 'milk', 'cheese', 'hummous', 'noodles'];
shopping;</pre>
 </li>
 <li>In this case, each item in the array is a string, but bear in mind that you can store any item in an array — string, number, object, another variable, even another array. You can also mix and match item types — they don't all have to be numbers, strings, etc. Try these:
  <pre class="brush: js">
var sequence = [1, 1, 2, 3, 5, 8, 13];
var random = ['tree', 795, [0, 1, 2]];</pre>
 </li>
 <li>Try creating a couple of arrays of your own, before you move on.</li>
</ol>

<h3 id="Accessing_and_modifying_array_items">Accessing and modifying array items</h3>

<p>You can then access individual items in the array using bracket notation, in the same way that you <a href="/en-US/Learn/JavaScript/First_steps/Useful_string_methods#Retrieving_a_specific_string_character">accessed the letters in a string</a>.</p>

<ol>
 <li>Enter the following into your console:
  <pre class="brush: js">
shopping[0];
// returns "bread"</pre>
 </li>
 <li>You can also modify an item in an array by simply giving a single array item a new value. Try this:
  <pre class="brush: js">
shopping[0] = 'tahini';
shopping;
// shopping will now return [ "tahini", "milk", "cheese", "hummous", "noodles" ]</pre>

  <div class="note"><strong>Note</strong>: We've said it before, but just as a reminder — computers start counting from 0!</div>
 </li>
 <li>Note that an array inside an array is called a multidimensional array. You can access an item inside an array that itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the <code>random</code> array (see previous section), we could do something like this:
  <pre class="brush: js">
random[2][2];</pre>
 </li>
 <li>Try further playing with, and making some more modifications to, your array examples before moving on.</li>
</ol>

<h3 id="Finding_the_length_of_an_array">Finding the length of an array</h3>

<p>You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the {{jsxref("Array.prototype.length","length")}} property. Try the following:</p>

<pre class="brush: js">
sequence.length;
// should return 7</pre>

<p>This has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. So for example:</p>

<pre class="brush: js">
var sequence = [1, 1, 2, 3, 5, 8, 13];
for(var i = 0; i &lt; sequence.length; i++) {
  console.log(sequence[i]);
}</pre>

<p>You'll learn about loops properly in a future article, but briefly, this code is saying:</p>

<ol>
 <li>Start looping at item number 0 in the array.</li>
 <li>Stop looping at the item number equal to the length of the array. This will work for an array of any length, but in this case it will stop looping at item number 7 (this is good, as the last item — which we want the loop to cover — is 6.</li>
 <li>For each item, print it out to the browser console with <code><a href="/en-US/docs/Web/API/Console/log">console.log()</a></code>.</li>
</ol>

<h2 id="Some_useful_array_methods">Some useful array methods</h2>

<p>In this section we'll look at some rather useful array-related methods that allow us to split strings into array items and vice versa, and add new items into arrays.</p>

<h3 id="Converting_between_strings_and_arrays">Converting between strings and arrays</h3>

<p>Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the {{jsxref("String.prototype.split()","split()")}} method. In it's simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings inbetween the separator as items in an array.</p>

<div class="note">
<p><strong>Note</strong>: OK, this is technically a string method, not an array method, but I've put it in with arrays as it goes well here.</p>
</div>

<ol>
 <li>Let's play with this, to see how it works. First, create a string in your console:
  <pre class="brush: js">
var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';</pre>
 </li>
 <li>Now let's split it at each comma:
  <pre class="brush: js">
var myArray = myData.split(',');
myArray;</pre>
 </li>
 <li>Finally, try finding the length of your new array, and retrieving some items from it:
  <pre class="brush: js">
myArray.length;
myArray[0]; // the first item in the array
myArray[1]; // the second item in the array
myArray[myArray.length-1]; // the last item in the array</pre>
 </li>
 <li>You can also go the opposite way using the {{jsxref("Array.prototype.join()","join()")}} method. Try the following:
  <pre class="brush: js">
var myNewString = myArray.join(';');
myNewString;</pre>
 </li>
</ol>

<h2 id="Adding_and_removing_array_items">Adding and removing array items</h2>

<p>We've not yet covered adding and removing array items — lets look at this now. We'll use the <code>myArray</code> array we ended up with in the last section. If you've not already followed that section, create the array first in your console:</p>

<pre class="brush: js">
var myArray = [ "Manchester", "London", "Liverpool", "Birmingham", "Leeds", "Carlisle" ];</pre>

<p>First of all, to add or remove an item at the end of an array we can use {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} respectively.</p>

<ol>
 <li>Let's use <code>push()</code> first — note that you need to include one or more items that you want to add to the end of your array. Try this:

  <pre class="brush: js">
myArray.push('Cardiff');
myArray;
myArray.push('Bradford', 'Brighton');
myArray;
</pre>
 </li>
 <li>The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
  <pre class="brush: js">
var newLength = myArray.push("Bristol");
myArray;
newLength;</pre>
 </li>
 <li>Removing the last item from the array is as simple as running <code>pop()</code> on it. Try this:
  <pre class="brush: js">
myArray.pop();</pre>
 </li>
 <li>The item that was removed is returned when the method call completes. You could also do this:
  <pre class="brush: js">
var removedItem = myArray.pop();
myArray;
removedItem;</pre>
 </li>
</ol>

<p>{{jsxref("Array.prototype.unshift()","unshift()")}} and {{jsxref("Array.prototype.shift()","shift()")}} work in exactly the same way, except that they work on the beginning of the array, not the end.</p>

<ol>
 <li>First <code>unshift()</code> — try the following commands:

  <pre class="brush: js">
myArray.unshift('Edinburgh');
myArray;</pre>
 </li>
 <li>Now <code>shift()</code>; try these!
  <pre class="brush: js">
var removedItem = myArray.shift();
myArray;
removedItem;</pre>
 </li>
</ol>

<h2 id="Active_learning_Printing_those_products!">Active learning: Printing those products!</h2>

<p>Let's return to the example we described earlier — printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers — Each of these marks a place where you have to add something to the code. They are as follows:</p>

<ol>
 <li>Below the <code>// number 1</code> comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called <code>products</code>.</li>
 <li>On the same line as the <code>// number 2</code> comment is the beginning of a for loop. In this line we currently have <code>i &lt;= 0</code>, which is a conditional test that causes the for loop to stop immediately, because it is saying "stop when <code>i</code> is no longer less than or equal to 0", and <code>i</code> starts at 0. We'd like you to replace this with a conditional test that stops the loop when <code>i</code> is no longer less than the <code>product</code> array's length.</li>
 <li>Just below the <code>// number 3</code> comment we want you to write a line of code that splits the current array item (<code>name:price</code>) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the <a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a> article for some help, or even better, look at the {{anch("Converting between strings and arrays")}} section of this article.</li>
 <li>As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the <a href="/en-US/Learn/JavaScript/First_steps/Strings#Numbers_versus_strings">first strings article</a>.</li>
 <li>There is a variable called <code>total</code> that is created and given a value of 0 at the top of the code. Inside the loop (below <code>// number 4</code>) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an <a href="/en-US/Learn/JavaScript/First_steps/Math#Assignment_operators">assignment operator</a> to do this.</li>
 <li>We want you to change the line just below // comment 5 so that the <code>itemText</code> variable is made equal to "current item name — $current item price", for example "Shoes — $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, so you should be OK with this.</li>
</ol>

<div class="hidden">
<h6 id="Playable_code">Playable code</h6>

<pre class="brush: html">
&lt;div class="output" style="min-height: 150px;"&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;

&lt;/div&gt;

&lt;textarea id="code" class="playable-code" style="height: 370px;"&gt;
var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
                'Underpants:6.99'
                'Socks:5.99'
                'T-shirt:14.99'
                'Trousers:31.99'
                'Shoes:23.99';

for(var i = 0; i &lt;= 0; i++) { // number 2
  // number 3

  // number 4
  
  // number 5
  itemText = 0;
  
  var listItem = document.createElement('li');
  listItem.textContent = itemText;
  list.appendChild(listItem);
}

totalBox.textContent = 'Total: $' + total.toFixed(2);
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar totalBox = document.querySelector(\'.output p\');\nvar total = 0;\nlist.innerHTML = \'\';\ntotalBox.textContent = \'\';\n\nvar products = [\'Underpants:6.99\',\n                \'Socks:5.99\',\n                \'T-shirt:14.99\',\n                \'Trousers:31.99\',\n                \'Shoes:23.99\'];\n\nfor(var i = 0; i &lt; products.length; i++) {\n  var subArray = products[i].split(\':\');\n  var name = subArray[0];\n  var price = Number(subArray[1]);\n  total += price;\n  itemText = name + \' — $\' + price;\n\n  var listItem = document.createElement(\'li\');\n  listItem.textContent = itemText;\n  list.appendChild(listItem);\n}\n\ntotalBox.textContent = \'Total: $\' + total.toFixed(2);';

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code', '100%', 600) }}</p>

<h2 id="Active_learning_Top_5_searches">Active learning: Top 5 searches</h2>

<p>A good use for array methods like {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.</p>

<p>In this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, The top 5 previous search terms are displayed in the list. When the number of terms gets to over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.</p>

<div class="note">
<p><strong>Note</strong>: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.</p>
</div>

<p>To complete the app, we need you to:</p>

<ol>
 <li>Add a line below the <code>// number 1</code> comment that adds the current value entered into the search input to the start of the array. This can be retrieved using <code>searchInput.value</code>.</li>
 <li>Add a line below the <code>// number 2</code> comment that removes the value currently at the end of the array.</li>
</ol>

<div class="hidden">
<h6 id="Playable_code_2">Playable code 2</h6>

<pre class="brush: html">
&lt;div class="output" style="min-height: 150px;"&gt;

&lt;input type="text"&gt;&lt;button&gt;Search&lt;/button&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;/div&gt;

&lt;textarea id="code" class="playable-code" style="height: 370px;"&gt;
var list = document.querySelector('.output ul');
var searchInput = document.querySelector('.output input');
var searchBtn = document.querySelector('.output button');

list.innerHTML = '';

var history = [];

searchBtn.onclick = function() {
  // we will only allow a term to be entered if the search input isn't empty
  if(searchInput.value !== '') {
    // number 1
    
    // empty the list so that we don't display duplicate entries
    // the display is regenerated every time a search term is entered.
    list.innerHTML = '';

    // loop through the array, and display all the search terms in the list
    for(var i = 0; i &lt; history.length; i++) {
      itemText = history[i];
      var listItem = document.createElement('li');
      listItem.textContent = itemText;
      list.appendChild(listItem);
    }

    // If the array length is 5 or more, remove the oldest search term
    if(history.length &gt;= 5) {
      // number 2

    }

    // empty the search input and focus it, ready for the next term to be entered
    searchInput.value = '';
    searchInput.focus();
  }
}
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar searchInput = document.querySelector(\'.output input\');\nvar searchBtn = document.querySelector(\'.output button\');\n\nlist.innerHTML = \'\';\n\nvar history = [];\n\nsearchBtn.onclick = function() {\n  if(searchInput.value !== \'\') {\n    history.unshift(searchInput.value);\n\n    list.innerHTML = \'\';\n\n    for(var i = 0; i &lt; history.length; i++) {\n      itemText = history[i];\n      var listItem = document.createElement(\'li\');\n      listItem.textContent = itemText;\n      list.appendChild(listItem);\n    }\n\n    if(history.length &gt;= 5) {\n      history.pop();\n    }\n\n    searchInput.value = \'\';\n    searchInput.focus();\n  }\n}';

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code_2', '100%', 600) }}</p>

<h2 id="Conclusion">Conclusion</h2>

<p>After reading through this article we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops being used to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!</p>

<p>The only thing left to do is work through this module's assessment, which will test your understand of the articles that came before it.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> — an advanced level guide to arrays and their cousins, typed arrays.</li>
 <li>{{jsxref("Array")}} — the <code>Array</code> object reference page — for a detailed reference guide to the features discussed in this page, and many more.</li>
</ul>

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/TBD", "Learn/JavaScript/First_steps")}}</p>
Revert to this revision