This post will discuss how to conditionally replace values in an array in JavaScript.

There are several ways to conditionally replace values in an array in JavaScript, depending on the criteria and the desired output. Here are some of the possible functions:

1. Using Array.map() function

The Array.map() function creates a new array with the results of calling a function on every element in the original array. We can use this function to replace values in an array based on a condition. For example, if we have an array of numbers and we want to replace all the negative numbers with zero, we can do this:

Download  Run Code

2. Using Array.forEach() function

The Array.forEach() function executes a function for each element in an array. We can use this function to modify the original array by accessing and replacing its elements by their index. For example, if we have an array of strings and we want to replace all the empty strings with "NA", we can do this:

Download  Run Code

3. Using a loop

We can also use a loop to iterate over the array and use a conditional statement to check and replace the values based on a condition. For example, if we have an array of objects and we want to replace all the objects that have a null value for a property with a default object, we can do this:

Download  Run Code

Output:

[
  { name: 'Anne', age: 25 },
  { name: 'Unknown', age: 0 },
  { name: 'Oliver', age: 30 },
  { name: 'Unknown', age: 0 },
  { name: 'Christopher', age: 45 }
]

That’s all about conditionally replacing values in an array in JavaScript.