To replace null with an empty string, go through the following steps:
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:
null
.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", ""]