Replace 0 with Null in JavaScript

Replace 0 with Null in JavaScript

The following are the examples provided to replace 0 with a null value in JavaScript.

Replacing 0 With Null Using Ternary Operator in JavaScript

val = 0;
val == 0 ? null : val;
console.log(val); // Output null

Using If/Else Condition in JavaScript

var row1 = [4,6,4,0,9];
var row2 = [5,2,0,8,1];
var row3 = [2,0,3,1,6];

var arrRows = [row1, row2, row3];

for (var i = 0; i < arrRows.length; i++) {
    for (var j = 0; j < arrRows[i].length; j++) {
        if (arrRows[i][j] == 0) {
            arrRows[i][j] = null;
        }
    }
}
console.log(row1);
console.log(row2);
console.log(row3);

Output:

[ 4, 6, 4, null, 9 ]
[ 5, 2, null, 8, 1 ]
[ 2, null, 3, 1, 6 ]

See also: