Caution: Javascript A || B expression is handy, but it also can cause tricky bugs

I had written the following code in a project

   ...
   return s && s.value || null

It works well for some days until a colleague did some code refactoring. In the beginning, s.value is a string value, and an empty string is not a valid value, so the code works well. After the refactoring, s.value became an integer, and this time 0 is a valid value. So you can imagine when s.value === 0 the code above will return null instead of 0. It leads to a bug!

Therefore please use the"A || B" expression with caution!

Comments

  1. Alan L said:

    It's 2021 and use the nullish coalescing operator.

    return s?.value ?? null
    
  2. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.