2

For example, this piece of code:

Number("") + Number("")

I expect to return "" (aka nothing) so I created this function

    function addthese(x, y){
        if (x != ""){
            asdf = Number(x) + Number(y)
            return  Number(asdf)
        } else {
            return ""
        }
    }

But for some reason this function returns NaN
Any help will be appreciated

Charlie
  • 22,886
  • 11
  • 59
  • 90
MatthewProSkils
  • 364
  • 2
  • 13
  • 1
    What input and output are you expecting? Running `addthese("", "")` already returns `""` – thammada.ts Jun 20 '20 at 06:02
  • beacuase when don't pass the argument, it will become undefined and Number(undefined) equals to `NaN` – gorak Jun 20 '20 at 06:02
  • You are just checking `X` for `""`, what about `Y`, and other values like `undefined` or `abc`? If `Number(Y)` is `NaN` then everything will be `NaN`. – Sandip Nirmal Jun 20 '20 at 06:19

3 Answers3

1

Perhaps, you might be calling the function without passing in parameters. I did some quick tests and that's the only way i managed to reproduce the "NaN" returning.

If that's the case, the function will "parse" an undefined value, which is not possible and you'll get that ugly NaN you got.

0

if you want to cache all cases related to undefined, null, false or "" please use the following code:

function addthese(x, y){
    return isNaN(x) || isNaN(y) ? "" :  Number(x) + Number(y)
}
vlad-grigoryan
  • 322
  • 3
  • 11
0

Even though the Number function can convert an empty string to 0, for any non-number string, it doesn't have a clue. So, NaN is returned.

console.log(Number(""));
console.log(Number(undefined));
console.log(Number("foo"));
Charlie
  • 22,886
  • 11
  • 59
  • 90