Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

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

  2. 2

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

Back

4/11

  1. 1. Introduction to Arrays
  2. 2. Creating Arrays
  3. 3. Accessing Array Elements
  4. 4. Changing Array Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: push()
  7. 7. Removing Elements: pop()
  8. 8. Searching an Array
  9. 9. Nested Arrays
  10. 10. Characters of a Text
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.