Skip to content

Logical Unary Assignment Operators &&= and ||= #31011

Closed
@colinvella

Description

@colinvella

Search Terms

  • unary
  • unary operators
  • unary logical operators
  • logical assignment
  • &&=
  • ||=

Suggestion

Typescript currently supports unary logical operators of the form x += y and x -= y, that are syntactically equivalent to x = x + y and x = x - y.

I would like to see the introduction of the logical equivalent of these operators, say &&= and ||=.

Use Cases

Expressions that take the form x = x && y and x = x || y could be expressed more succinctly by x &&= y and x ||= y respectively, using the proposed operators.

It is often the case that deeply nested properties in an object tree need to be assigned a fallback using the || operator. The latter operator, being binary, would require repeating the property drill-down expression.

Examples

foo.bar.baz = foo.bar.baz || "default";

With the proposed operators, this could be expressed more succinctly as

foo.bar.baz ||= "default";

The operators &&= and ||=would hence by syntactic sugar for the binary equivalents && and || where the result of the expressions are assigned to the first operator in the original binart expression. That is:

x &&= y is syntactically equivalent to x = x && y
x ||= y is syntactically equivalent to x = x || y

All rules for the equivalent expressions using the existing binary operators apply.

Please note that no change is required to existing operators or other language features.

Checklist

My suggestion meets these guidelines:

  • [Y] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [Y] This wouldn't change the runtime behavior of existing JavaScript code
  • [Y] This could be implemented without emitting different JS based on the types of the expressions
  • [Y] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [N] This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions