freeCodeCamp/guide/english/certifications/javascript-algorithms-and-d.../es6/mutate-an-array-declared-wi.../index.md

3.4 KiB

title
Mutate an Array Declared with const

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

Problem Explanation:

Reassign the values of the const variable s using various element assignment.

:speech_balloon: Hint: 1

  • You can change array values on const like you can with var or let.

try to solve the problem now

:speech_balloon: Hint: 1

  • To access array value use array[index]

try to solve the problem now

Spoiler Alert!

warning sign

Solution ahead!

:beginner: Basic Code Solution:

    const s = [5, 7, 2];
    function editInPlace() {
      "use strict";
      s[0] = 2;
      s[1] = 5;
      s[2] = 7;
    }
    editInPlace();

:rocket: Run Code

Code Explanation:

Trying to reassign a read-only const variable will throw an error, but by using various element assignment you can access and change the value of an array just like you would with let or var.

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.