When working with arrays, you often need to modify the elements stored in them. In JavaScript, you can modify array elements by assignment.
To modify an element in an array, you can use the assignment operator (=
) followed by the new value you want to assign to the element.
For example, let's say we have an array numbers
that contains three elements: 1, 2, and 3. If we want to change the second element from 2 to 4, we can do it like this:
1const numbers = [1, 2, 3];
2
3numbers[1] = 4;
4console.log(numbers); // Output: [1, 4, 3]
In the above example, numbers[1] = 4;
modifies the second element in the array to the value 4. The console.log
statement then outputs the modified array: [1, 4, 3]
.
It's important to note that when you modify an element in an array, you are changing the original array itself. If there are any other variables that reference the same array, they will reflect the changes as well.
Modifying array elements by assignment allows you to update the values stored in the array and make changes to the array data as needed.