Home

How to Change Array Element Values in JavaScript

|
|  Updated:  
2016-03-26 07:26:26
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

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:

    console.log(people);

    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:

    console.log(people);

    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.

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.