This rule enforces the use of optional chaining (?.) over logical AND (&&) for property access when the same object is being checked and accessed.
- const name = user && user.name
+ const name = user?.name
- const email = user && user.profile && user.profile.email
+ const email = user?.profile?.email
- const count = data && data.items && data.items.length
+ const count = data?.items?.length- const result = api && api.getData()
+ const result = api?.getData()
- const user = service && service.getUser(id)
+ const user = service?.getUser(id)
- const processed = data && data.filter().map()
+ const processed = data?.filter()?.map()- const value = obj && obj[key]
+ const value = obj?.[key]
- const item = array && array[index]
+ const item = array?.[index]
- const prop = config && config[setting]
+ const prop = config?.[setting] function getUserName(user) {
- return user && user.name
+ return user?.name
}
- const getUserEmail = user => user && user.profile && user.profile.email
+ const getUserEmail = user => user?.profile?.email- const greeting = `Hello ${user && user.name}!`
+ const greeting = `Hello ${user?.name}!`
- const status = `Count: ${data && data.items && data.items.length}`
+ const status = `Count: ${data?.items?.length}`This rule only applies to:
- ✅ Logical AND (
&&) operators where the same object is being checked and accessed:object && object.property→object?.propertyobject && object.method()→object?.method()object && object[key]→object?.[key]
This rule does NOT apply to:
- ❌ Logical AND (
&&) with different objects (user && profile.name) - ❌ Logical AND (
&&) with literals (user && 'active') - ❌ Logical AND (
&&) with function calls (user && getName()) - ❌ Logical OR (
||) operators - ❌ Already using optional chaining (
user?.name) - ❌ Other logical operators (
!,??)
The rule provides auto-fix suggestions that replace && with ?.:
user && user.name→user?.nameuser && user.getName()→user?.getName()obj && obj[key]→obj?.[key]api && api.getData(id)→api?.getData(id)user && user.profile && user.profile.email→user?.profile?.email