JavaScript

JavaScript

Made by DeepSource

Logical operator can be refactored to optional chain JS-W1044

Anti-pattern
Minor
Autofix

The optional chaining operator can be used to perform null checks before accessing a property, or calling a function.

Using && for this purpose is no longer required.

Bad Practice

function getUsernameFromId(id: number): string | undefined {
  const user = db.getUser(id)
  return user && user.name
}

someFunc && someFunc()
//        ^~~~ not necessary

maybeArray && maybeArray[index]
//          ^~~~ not necessary

Recommended

function getUsernameFromId(id: number): string | undefined {
  const user = db.getUser(id)
  return user?.name
}

someFunc?.()

maybeArray?.[index]