Setting Elements by Index
What you'll learn: How to change the value stored at a specific position in an array.
Assigning New Values to Array Positions
You've learned how to read array elements using bracket notation and an index number. Now you can also write to those positions. Just like you read values with myArray[0], you can assign new values using the same bracket notation with the assignment operator (=).
Think of an array like a row of numbered mailboxes. You already know how to check what's inside mailbox #2. Now you're learning to replace what's in there with something new — the mailbox stays in the same position, but its contents change.
How It Works
The syntax is straightforward:
let colors = ['red', 'green', 'blue'];
// Change the first element (index 0)
colors[0] = 'yellow';
// Now colors is ['yellow', 'green', 'blue']
// Change the last element (index 2)
colors[2] = 'purple';
// Now colors is ['yellow', 'green', 'purple']
You specify the index in brackets, then use = to assign the new value. The array is modified in place — you're changing the existing array, not creating a new one.
Important Details
Remember that arrays use zero-based indexing, so the first element is at index 0. You can overwrite any existing element by assigning to its index position. The array's length stays the same when you replace an existing element.
let numbers = [10, 20, 30];
numbers[1] = 99;
// numbers is now [10, 99, 30]
Key Takeaway: Use bracket notation with an index and the assignment operator to change values stored in array positions: arrayName[index] = newValue.