JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to replace null with 0 in an array using JavaScript?

To replace null with 0 in an array, go through the following steps:

  1. First, call the array forEach() method.
  2. Then, pass a callback function with two parameters, element, and index, to the forEach() method.
  3. Inside the callback function, compare each array element with null.
  4. If an element is null, set the value to zero at that index position.
let arr = [24, 12, null, 21, 8, null, 33, 5];
arr.forEach((element, index) => {
  if(element === null){
    arr[index] = 0;
  }
});

console.log(arr); //[24, 12, 0, 21, 8, 0, 33, 5]

The forEach() method is used to iterate through an array. It accepts two parameters:

  1. Callback function: This function is called for each element of an array.
  2. thisArg: It is optional. When you use this variable inside the callback function, then this points to the value passed to the thisArg parameter.

Another way to replace null with 0 is to use the map() method.

The map() method updates each array element without modifying the original array.

Inside the callback function of the map() method, compare each element with null. If an element is null, return 0; otherwise, return the element.

let arr = [24, 12, null, 21, 8, null, 33, 5];
let result;

result = arr.map(element => {
  if(element === null){
    return 0;
  }else{
    return element;
  }
});

console.log(result); //[24, 12, 0, 21, 8, 0, 33, 5]

Recommended Posts