Updated at August 21, 2020
There are two ways to create, update, and delete items to an array in JavaScript. The first approach is by using the mutable methods which will change the array itself.
The second approach is by using the immutable methods, which will return a new array that contains a new updated value. This could be very useful if your using Redux or changing component state in React.
Let's say we have an array that contains a few items.
const list = ["Item 1", "Item 2", "Item 3"]
The mutable way:
const newItem = "Item 4"
list.push(newItem)
The immutable way:
const newItem = "Item 4"
const newList = list.concat([newItem])
Result:
[
"Item 1",
"Item 2",
"Item 3",
"Item 4"
]
The mutable way:
const itemIndex = 1
const newItem = "Item 2 (updated)"
list[itemIndex] = newItem
The immutable way:
const itemIndex = 1
const newItem = "Item 2 (updated)"
const newList = list.map((item, index) => {
return index === itemIndex ? newItem : item
})
Result:
[
"Item 1",
"Item 2 (updated)",
"Item 3"
]
The mutable way:
const itemIndex = 1
list.splice(itemIndex, 1)
The immutable way:
const itemIndex = 1
const newList = list.filter((item, index) => {
return index !== itemIndex
})
Result:
[
"Item 1",
"Item 3"
]
I'm a software engineer specialized in iOS and full-stack web development. If you have a project in mind, feel free to contact me and start the conversation.