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
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • By
    Retrieve Your Gmail Emails Using PHP and IMAP

    Grabbing emails from your Gmail account using PHP is probably easier than you think. Armed with PHP and its IMAP extension, you can retrieve emails from your Gmail account in no time! Just for fun, I'll be using the MooTools Fx.Accordion plugin...

  • By
    Comment Preview Using MooTools

    Comment previewing is an awesome addition to any blog. I've seen really simple comment previewing and some really complex comment previewing. The following is a tutorial on creating very basic comment previewing using MooTools. The XHTML You can set up your XHTML any way you'd like.

Discussion

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