JavaScript, How to update an array element

In JavaScript, developers need that they need to update the value of an array element. It is just as easy as assigning a new value to a variable using an assignment operator. So in this article, we will see it

Update array value with static index

let colours = ["Red", "Orange", "Yellow", "Olive", "Green"];

console.log(colours);
// Output -> ["Red", "Orange", "Yellow", "Olive", "Green"]

colours[2] = "Blue";
console.log(colours);
// Output -> ["Red", "Orange", "Blue", "Olive", "Green"]

Console screenshot for update array element

Update Array Element
Update Array Element

Update array value by searching value

let colours = ["Red", "Orange", "Yellow", "Olive", "Green"];

console.log(colours);
// Output -> ["Red", "Orange", "Yellow", "Olive", "Green"]

let index = colours.indexOf("Yellow");
colours[index] = "Blue";
console.log(colours);
// Output -> ["Red", "Orange", "Blue", "Olive", "Green"]

// One-liner
colours[colours.indexOf("Green")] = "Aqua";
console.log(colours);
// Output -> ["Red", "Orange", "Blue", "Olive", "Aqua"]

Console screenshot for an element searching by value with indexOf method

Update Array Element Searching By Value With IndexOf Method
Update Array Element Searching By Value With IndexOf Method

Hope you like this!

Keep helping and happy 😄 coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳