Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

Logical Assignment Operators

October 28, 2020
javascripttypescript

We regularly need to implement conditional logic in the apps we build. This post covers a new terse syntax that we can now use for different logical operators in both JavaScript and TypeScript.

Logical Assignment Operators

Logical OR assignment

When writing code, we often set a variable to some value if the variable is currently falsy. Consider the example below:

function getDefaultValue() {
  console.log("getDefaultValue");
  return 1;
}

let score: number | null = null;
score = score || getDefaultValue();console.log(score);

In this example, score is assigned to the result of getDefaultValue because score was originally falsy.

Logical OR assignment 1

If score is originally truthy, then the second argument is not evaluated:

let score: number | null = 9;score = score || getDefaultValue();
console.log(score);

Logical OR assignment 2

The new Logical OR assignment operator gives us a slightly shorter syntax for this pattern:

let score: number | null = null;
score ||= getDefaultValue();console.log(score);

Logical OR assignment 1

Logical nullish assignment

Use of the nullish coalescing operator (??) in the previous example means that the default value is only applied if the variable is null or undefined:

let score: number | null = 0;
score = score ?? getDefaultValue();console.log(score);

Nullish assignment operator 1

The new Logical nullish assignment operator gives us a slightly shorter syntax for this pattern:

score ??= getDefaultValue();

Logical AND assignment

We regularly use the logical AND operator (&&) for expressing conditional logic. Some example code is below:

let value = "F";
let valid: boolean = true;
valid = valid && value !== "";valid = valid && value.length > 2;console.log(valid);

Logical AND

The new Logical AND assignment operator gives us a slightly shorter syntax for this pattern:

valid &&= value !== "";
valid &&= value.length > 2;

Nice!

Wrap up

The new logical assignment operators provide terser syntax for some of the conditional code we write.

The syntax is supported in all major browsers other than IE. Babel supports it with the plugin-proposal-logical-assignment-operators plugin, and TypeScript has recently added support for it in 4.0.

Did you find this post useful?

Let me know by sharing it on Twitter.
Click here to share this post on Twitter

If you to learn more about TypeScript, you may find my free TypeScript course useful:

Take a look