Update an Item at a Specific Position in JavaScript
In JavaScript, arrays help you manage collections of values — like fruits, tasks, or products. But what if one of those values needs to change? Maybe a user edited their name or you need to mark a task as completed. Updating an item at a specific position is a simple, direct task — and one of the most common things you'll do when working with data. This tutorial walks you through various ways to modify an array element by its index, using practical examples that are clear and beginner-friendly.
Method 1: Using Bracket Notation and Index
This is the most straightforward way to update a value. Since arrays are zero-indexed in JavaScript, you can use the index directly with bracket notation to assign a new value to an existing item.
const fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry";
console.log(fruits);
["apple", "blueberry", "cherry"]
Method 2: Using a Variable for the Index
Instead of hardcoding the index, you can store it in a variable. This is helpful when the position is determined dynamically — for example, through user interaction or calculations in a loop.
const tasks = ["Clean", "Cook", "Read"];
let position = 2;
tasks[position] = "Write";
console.log(tasks);
["Clean", "Cook", "Write"]
Method 3: Using the map()
Method (Immutable Update)
If you want to avoid mutating the original array — for example, in React or functional programming — you can use map()
to create a new array with the updated value. This is a clean and declarative way to make changes.
const items = ["Item 1", "Item 2", "Item 3"];
const updateIndex = 1;
const updatedItems = items.map((item, index) =>
index === updateIndex ? "Updated Item 2" : item
);
console.log(updatedItems);
["Item 1", "Updated Item 2", "Item 3"]
When to Use Each Method
- Bracket notation with direct index: Use this when the update is simple and you’re okay modifying the original array.
- Bracket notation with variable: Useful for updates where the index is calculated or derived from logic.
map()
method: Best when working in a functional style, especially in frameworks like React, where immutability is preferred.
Comments
Loading comments...