Replacing Elements in an Array

By: Dusty Arlia
Published on September 19, 2012
Last Updated on Tuesday, July 14, 2015 at 5:37 PM
Total Updates: 5

Sometimes when you are adding an item to an array, you would like to replace an existing item. In this case what you should do is use the array's name followed by square brackets ([ ]). Then in between those square brackets, insert the index number of the existing item that you would like to replace. Here's how that code would look like:

var fullNames = ['Kevin Kolb',
                 'Matt Ryan',
                 'Joe Flacco',
                 'Ryan Fitzpatrick',
                 'Cam Newton',
                 'Jay Cutler',
                 'Andy Dalton',
                 'Brandon Weeden',
                 'Tony Romo',
                 'Peyton Manning',
                 'Matthew Stafford'];
fullNames[2] = 'Dusty Arlia';

In the code above the string literal 'Joe Flacco' gets replaced with the new string literal 'Dusty Arlia'. Remember that the string 'Kevin Kolb' has an index number of 0, as do all array elements in the first position.