js Advanced
Immutable add, edit, delete operations
Open this example in our interactive code editor to experiment with it.
Try the EditorImmutability with rest spread operator
let items = [];
// Add item to the beginning of items array using rest operator
const addItemToStart = (newItem) => {
items = [newItem, ...items];
}
// Add item to the end of items array using rest operator
const addItemToEnd = (newItem) => {
items = [...items, newItem];
}
// Edit item using .map method, if id matches, use rest operator to override
// item properties with updatedItem, otherwise return item as is
const editItem = (updatedItem) => {
items = items.map((item) => {
if (updatedItem.id === item.id) {
return {
...item,
...updatedItem
}
}
return item;
})
}
// Delete item using .filter method, if id matches, delete it from items array
const deleteItem = (idToRemove) => {
items = items.filter((item) => item.id !== idToRemove);
}
Summary
- Rest spread operator is helpful when it comes to working with arrays and objects.
- Add, edit, delete functions can be used on any object structure and should work well with the array of those objects.
Try this in our interactive code editor
Practice hands-on with our built-in code sandbox.
Open Code Editor
Adrian Bigaj
Creator of BigDevSoon
Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.
Related Pills
js Advanced
Method chaining
Method chaining is a helpful pattern to learn in programming.
js Intermediate
JavaScript multiple condition checks
Checking multiple values in JavaScript often leads to redundant, boilerplate code - let's use .includes method to fix that.
js Intermediate
Convert JavaScript data structures
Converting data structures is a day-to-day job as a Developer.