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
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

  • By
    CSS Vertical Centering

    Front-end developing is beautiful, and it's getting prettier by the day. Nowadays we got so many concepts, methodologies, good practices and whatnot to make our work stand out from the rest. Javascript (along with its countless third party libraries) and CSS have grown so big, helping...

  • By
    Spoiler Prevention with CSS Filters

    No one likes a spoiler.  Whether it be an image from an upcoming film or the result of a football match you DVR'd, sometimes you just don't want to know.  As a possible provider of spoiler content, some sites may choose to warn users ahead...

Discussion

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