Changing Array Elements

You can also change an element of an array. Write the array's name and the index in square brackets, as when you read the element, and assign it a new value with =, just as you would assign a value to a variable:

const resolutions = ["Write a diary", "Take a falconry course", "Learn to juggle"];
resolutions[1] = "Take a painting course";
console.log(resolutions);

This prints:

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

The element at index 1 now has a new value. The other elements stay the same.

Notice that resolutions was created with const, and yet you could change its element. That's because const only means that the variable always holds the same array. What's inside the array can change. What you can't do is store a different array in the variable:

const numbers = [1, 2];
numbers[0] = 5; // Fine: changes an element
numbers = [3, 4]; // Error: a constant can't get a new array

The last line stops the program with the error TypeError: Assignment to constant variable., which you've already seen with constants. If you need to put a whole new array into a variable, create the variable with let. Most of the time, though, you keep one array and change its elements, so const is the usual choice for arrays.

Instructions

Tim has moved to another team, and Daniel has taken his place. Below the console.log(), change the second element of coworkers to "Daniel".

Then print coworkers again. The console now shows the array before and after the change.

Start programming for free

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

Or sign up with:

Back

4/11

Next