Code Highlights logo

Learn

Arrays

Update Elements

To update an element in an array, we use the following syntax:

1arrayName[index] = newValue;

Examples:

Let's take a look at some examples to better understand the concept:

  1. Updating a Single Element:
    1let fruits = ['apple', 'banana', 'cherry'];
    2fruits[0] = 'orange';
    3// fruits array will now be ['orange', 'banana', 'cherry']
    In this example, the element at index 0 (which is 'apple') is updated to 'orange'. The resulting array will have 'orange' at the first position.
  2. Updating Multiple Elements:
    1let numbers = [1, 2, 3, 4, 5];
    2numbers[2] = 6;
    3numbers[4] = 7;
    4// numbers array will now be [1, 2, 6, 4, 7]
    Here, we update the elements at index positions 2 and 4 in the 'numbers' array. The values at those positions are modified to 6 and 7, respectively.

Instructions

1.

Declare a variable called index and assign it the value 2.

2.

Use the index variable to update the element at that index in the fruits array to "kiwi".

3.

Console log the updated fruits array.

Sign up to start coding

Already have an account?

Sign In

Course content