Replace all the null values with a specific value in an array in JavaScript

In this tutorial on JavaScript arrays, we will cover how to replace all null values with a specific value.

Table of Contents

INTRODUCTION

FINDING THE LENGTH OF AN ARRAY

CREATING A FUNCTION 

 

INTRODUCTION

In this tutorial, we will create a function that uses a for loop based on the length of an array. We will include an if statement within the loop to check for a specific condition. If the condition is met, the function will replace any null values in the array with the specified values.

FINDING THE LENGTH OF AN ARRAY

let myArray=[1,null,3,4,null,8,null,9];
//  to find length we use length keyword
let arrayLength=myArray.length;
console.log(arrayLength)
OUTPUT:
8

CREATING A FUNCTION

function To_Replace_Null_With_aValue(myArray,Length,spvalue){
        for (i=0; i<Length; i++){
            if( myArray[i]===null){
               myArray[i]= spvalue;
             }
        }
        return myArray;
       }

let nullArray=[1,null,3,4,null,9];
let Length=nullArray.length;
console.log(To_Replace_Null_With_aValue(nullArray,Length,8));
OUTPUT:
[ 1, 8, 3, 4, 8, 9 ]

To replace null values with a specific value in an array, you can create a function that takes three arguments: the array in which you want to make changes, the length of the array, and the specified value that needs to be replaced. Iterate over the array’s length and get the index values using a for loop. Then, use an if condition to keep track of the index values and retrieve the values in the array. To replace the null values, check if the array value is null using another if condition. If it is null, replace it with the specified value passed to the function as an argument.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top