JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to replace null with empty string in JavaScript Array?

To replace null with an empty string, go through the following steps:

  1. Call the map() method on the array.
  2. Inside the callback function of the map() method, compare each element with null.
  3. If an element is equal to null, return an empty string; otherwise, return the element.
let fastFood = ['Pizza', 'Chips', null, 'Burger', null, "Taco", null];
let result = fastFood.map(element => {
  if(element === null){
    return "";
  }else{
    return element;
  }
});
 
console.log(result);

Output

["Pizza", "Chips", "", "Burger", "", "Taco", ""]

The map() method is one of the array iteration methods used to transform each element of an array. It does not modify the original array.

The array map() method accepts a callback function that is called for each element of the array.

let arr = [11,22,33,44,55];
let result = arr.map(element => {
	return element + 10;
});
console.log(`Original array: ${arr}`);
console.log(`Modified array: ${result}`);

Output

"Original array: 11,22,33,44,55"
"Modified array: 21,32,43,54,65"

An alternative approach to replace null with empty string in an array is to use array forEach() method.

Follow the below steps if you want to replace null with empty string using the forEach() method:

  1. First, create an empty array.
  2. Call the forEach() method on the array where you want to replace null with an empty string.
  3. Inside the callback function of the forEach() method, compare each element with null.
  4. If an element is null, push the empty string to the array created in Step 1; otherwise, push the element.
let result = [];
let fastFood = ['Pizza', 'Chips', null, 'Burger', null, "Taco", null];

fastFood.forEach(element => {
  if(element === null){
    result.push("");
  }else{
    result.push(element);
  }
});
 
console.log(result);

Output

["Pizza", "Chips", "", "Burger", "", "Taco", ""]

Recommended Posts