DEV Community

Discussion on: Some Things About JSON That You May Have Missed

Collapse
 
stephenmirving profile image
Stephen Irving • Edited

Just so you know, including multiple return paths for functions is an anti-pattern/code-smell. It is a best practice for a function to only have a single return path if that is possible. So, for example, in your third to last snippet, you could have written the replacer function like this instead and have what it returns be the same (I also fixed your NaN check to use Number.isNaN() because using equality to check against NaN will not work as expected):

const replacer = (key, value) => (
  typeof value === 'undefined'
    ? 'undefined'
    : (
      value instanceof Function || Number.isNaN(value) || value === Infinity
        ? value.toString()
        : value
    )
);
Collapse
 
petergabriel2 profile image
PeterGabriel2 • Edited

Absolutely wrong! In every case is switch more readable than joined or/and superlongline. More easy to update. And you will not make error in it so easily like in bunch of writeonly code you just wrote.

Collapse
 
aumayeung profile image
John Au-Yeung

I think ternary operator shouldn't be nested. It's harder to read than if or switch like you said.