Menu
Coddy logo textTech

Modifying Arrays

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 59 of 77.

In addition to accessing the elements of an array, you can also modify them. To modify a specific element in an array, you can assign a new value to it using its index.

Here's an example:

let myArray = ["apple", "banana", "cherry"]
myArray[1] = "orange";
console.log(myArray);

Output:

["apple", "orange", "cherry"]

banana was changed to an orange

challenge icon

Challenge

Easy

Create a function named changeElement that receives 3 arguments:

  • First argument is an array
  • Second argument is an index
  • Third argument is a new element

The function will return the modified array by changing the element in an index that is stored in the second argument with the value in the third argument.

For example, with the following arguments: changeElement<strong>(</strong>[1, 2, 3], 0, 9) the function will return [9, 2, 3]

Cheat sheet

To modify an array element, assign a new value using its index:

let myArray = ["apple", "banana", "cherry"];
myArray[1] = "orange";
console.log(myArray); // ["apple", "orange", "cherry"]

Try it yourself

function changeElement(arr, index, newElement) {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals