How to Change Array Element Values in JavaScript - dummies

How to Change Array Element Values in JavaScript

By Chris Minnick, Eva Holland

JavaScript gives you several ways to modify arrays. The first way is to give an existing array element a new value. This is as easy as assigning the value. Follow these steps in your JavaScript Console to see how this works:

  1. Create a new array with the following statement:

    var people = ["Teddy","Cathy","Bobby"];
  2. Print out the values of the array elements with this statement:


    The JavaScript Console returns the same list of elements that you put in in the previous step.

  3. Change the value of the first element by entering this ­statement, and then press Return or Enter:

    people[0] = "Georgie";
  4. Print the values of the array’s element now, using the ­following statement:


    The value of the first array element has been changed from “Teddy” to “Georgie”.

Now it’s your turn. Can you modify the array so that it contains the following list of names, in this order?

Mary, Bobby, Judy, Eddie, Herbie, Tony

When you have lists of names, or lists of anything, there are many things that you can do with them, such as sorting them, adding to and removing from them, comparing them, and much more.