Logical Assignment Operators

By  on  

I love JavaScript, it's my favorite programming language, but I love dipping into other languages because they offer a new perspective on coding paradigms. There've been syntax additions to JavaScript that I've seen I found interesting (think ?? in optional chaining) and now we get more -- logical assignment operators. Let's check out how they can be used!

||=

Or-Or-Equals is used to assign a value when one doesn't exist:

let name;
const defaultName = "Guest";

name ||= defaultName;
// name >> "Guest"

// Equivalent: name || (name = defaultName);

??=

Question-Question-Equals assigns value when the value is undefined:

const j = 1;
j??= 10
// j >> 1

x = undefined;
x ??= 10
// x >> 10

&&=

And-And-Equals assigns value to the last in line when both are defined:

let name;
const defaultName = "Guest";

name &&= defaultName;
name >> undefined

// Both have values
let name = "David";
const defaultName = "Guest";

name &&= defaultName;
// name >> "Guest"

// Equivalent: name && (name = defaultName);

I do worry, at least in the short term, that this new syntax could be hard to maintain, but just like every other new language feature, we'll get used to it!

Recent Features

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

Incredible Demos

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!