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 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
Hope you like this!
Keep helping and happy 😄 coding