Updating Array Elements

In the previous exercise, we learned how to access array elements using their indices. Now we will look at how we can update the values of these elements.

Updating an array element is simple. We use the same notation we used to access elements, and assign a new value using the = operator as if we were assigning a value to a variable.

Let's look at an example:

const newYearResolutions = ["Write a diary", "Attend a falconry course", "Learn to juggle"];

Suppose we want to change the second resolution. We use the following code, where we put a new element at index 1:

newYearResolutions[1] = "Attend a painting course";

Now the array newYearResolutions will look like this:

["Write a diary", "Attend a painting course", "Learn to juggle"]

Note that even though newYearResolutions is a constant, we can change the elements of the array. The only thing we cannot do is replace the entire array:

const constantArray = [1, 2];
constantArray = [3, 4]; // Causes an error

let array = [1, 2];
array = [3, 4]; // Does not cause an error

Instructions

Change the value of the second coworker to "Daniel".

Print the value of the variable coworkers.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/10

Updating Array Elements | Start Coder