Skip to content

Explicit comparisons for strings are a bad practice because they don't account for null/undefined. #1719

Description

@distinctdan

For strings, the guide states:

15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.

// bad
if (name) {
  // ...
}

// good
if (name !== '') {
  // ...
}

However, this is actually a bad practice for strings because it doesn't account for other falsey values like undefined or null. The developer may not always control the initial state of a variable if it's loaded from an API, so using explicit checks against empty strings is likely to result in subtle bugs in your code. To truly be safe, you'd have to do if (name !== undefined && name !== null && name !== '') {, which is pretty terrible.

For most things, you only care about "do I have a value". For this, the "bad" check is actually the most elegant and safe way to do this.

if (name) {

On StackOverflow, the "bad" answer has by far the most votes as well: https://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript/154068#154068

Would you guys consider changing this?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions