0

I am checking for undefined and want to replace with ""

I have:

let values = [ ['header1','header2'], 
                ['AAA', undefined],
                [2, 'BB'],
                [undefined, 'CCC'],
                ['AAA', 4],
              ];
values.forEach(function (row) {
  row.forEach(function(col) {
    col= col===undefined ? "":col;
  });
});

It returns the original array values.

But I am expecting

[ ['header1','header2'], 
  ['AAA', ""],
  [2, 'BB'],
  ["", 'CCC'],
  ['AAA', 4],
 ];

What am I doing wrong?

Einarr
  • 214
  • 2
  • 14
  • 1
    `row.forEach(function(col,idx,arr) { arr[idx]= col===undefined ? "":col;...` – cmgchess Mar 19 '23 at 16:14
  • You can't compare to undefined directly, you'll have to use `typeof(col)==="undefined"` or if you're fine with null being replaced too `col ?? ""` – Sweet Sheep Mar 19 '23 at 16:17
  • 2
    @SweetSheep Comparing `=== undefined` is totally fine, `typeof` is not needed. – Bergi Mar 19 '23 at 16:18
  • 1
    @SweetSheep of course you can compare to `undefined` directly ... `a === undefined` is equivaltent to `typeof a === "undefined"` – derpirscher Mar 19 '23 at 16:19
  • 1
    @derpirscher they're not quite equivalent - if `a` hasn't even been declared then `a === undefined` will be a `ReferenceError`, but `typeof a === "undefined"` will be `true`, with no error. But other than that edge case, you're correct that they're identical. – Robin Zigmond Mar 19 '23 at 16:23
  • 1
    @RobinZigmond If you were to nitpick, `undefined` could also be shadowed, but that's obscure. And `col` absolutely has been declared in the above example. – Bergi Mar 19 '23 at 16:42
  • in the code as shown in the OP, sure. I was responding just to the comment which, by referring to a variable `a` that doesn't exist in the OP, seemed to be making a general point – Robin Zigmond Mar 19 '23 at 16:46

0 Answers0