Menu Home

Assignment Operators

Hi everyone, and welcome to another exciting edition of Boring JavaScript. This week, we’re going to cover something most people gloss over but surprising know little about (at least in my experience) – JavaScript assignment operators.

Don’t like to read? Then watch the video.

Assign A to B

We all know about assigning a value to a variable using the equals sign (“=”). Assignment operators are modifiers of that sign in that they also perform an operation on the value being assigned before the assignment actually happens.

What do we mean? Let’s take a look at one example:

let numberOfAnimals = 5;
const animalsToAdd = ["Cat", "Dog", "Horse"];

// The 'standard' way of adding a number to a variable
numberOfAnimals =  numberOfAnimals + animalsToAdd.length;

// The 'assignment operator' way to adding a number to a variable
numberOfAnimals += animalsToAdd.length;

Line 5 shows the traditional method of adding the value of one variable to another. Line 8 shows the ‘assignment operator’ way of doing the same thing. Both lines of code give your exact same result – but by using assignment operators, your code becomes a little easier to read and maintain.

Assignment operators are therefore a convenience method of writing code that can simplify the maintenance of your code.

Let’s Get a Group Together

The assignment operators can generally be grouped into three sections. Let’s take a look at each.

Math

let myNumber = 1;

// Addition
myNumber += 1;
console.log(`After +=: ${myNumber}`);

// Subtraction
myNumber -= 1;
console.log(`After -=: ${myNumber}`);

// Multiplication
myNumber *= 5;
console.log(`After *=: ${myNumber}`);

// Division
myNumber /= 5;
console.log(`After /=: ${myNumber}`);

// Exponentiation
myNumber = 2;
myNumber **= 5;
console.log(`After **=: ${myNumber}`);

/* output
After +=: 2
After -=: 1
After *=: 5
After /=: 1
After **=: 32
*/

Bitwise

If you are not familiar with bitwise operations, it’s the process of working on variables at the bit level. If you are doing byte level coding (encryption comes to mind), you will use these a lot. For reference, a typical JavaScript number is internally represented by four bytes, or thirty-two bits.

let myNumber = 1;
// Shift bits left - which basically multiplies the number by 2
myNumber <<= 1;
console.log(`After <<=: ${myNumber}`);

// Shift bits right, and keep the sign. Basically divides the number by 2.
myNumber >>= 1;
console.log(`After >>=: ${myNumber}`);

// Shift bits right, do not keep the sign. Divides by 2 like the example above, but since the 
// sign of the number is always kept in the 31st or last bit of the number, you can get some
// unexpected results when using this on a negative number.
myNumber = -1
myNumber >>>= 1;
console.log(`After >>>=: ${myNumber}`);

// AND the bits. Perform a bit-level Logical AND on all the bits. That means:
// 1 & 1 = 1
// 1 & 0 = 0
// 0 & 1 = 0
// 0 & 0 = 0
myNumber = 1;
myNumber &= 3;
console.log(`After &=: ${myNumber}`);

// OR the bits. Perform a bit-level Logical OR on all the bits. That means:
// 1 | 1 = 1;
// 1 | 0 = 1;
// 0 | 1 = 0;
// 0 | 0 = 0;
myNumber |= 4;
console.log(`After |=: ${myNumber}`);

// XOT the bits. Perform a bit-level Logical Exclusive OR on all the bits. That means:
// 1 ^ 1 = 0
// 1 ^ 0 = 1
// 0 ^ 1 = 1
// 0 ^ 0 = 0
myNumber ^= 3;
console.log(`After ^=: ${myNumber}`);

/* output
After <<=: 2
After >>=: 1
After >>>=: 2147483647
After &=: 1
After |=: 5
After ^=: 6
*/

Logical Operators

Logical operators work by returning one side of the comparison or the other based upon the operator. In the following code, I’m showing a ‘myNumber’ and a ‘yourNumber’ to show you how each one works.

// Logical AND: The assignment occurs if the value on the left is 'truthy'
// otherwise, no assignment is made;
let myNumber = 1;
let yourNumber = 0;
myNumber &&= 2;
yourNumber = yourNumber && 2;
console.log(`After &&=: ${myNumber} (${yourNumber})`);

// Logical OR: The assignment occurs if the value on the left is 'falsy'
// otherwise, no assignment is made; 
myNumber = 1;
yourNumber = 0;
myNumber ||= 2;
yourNumber = yourNumber || 2;
console.log(`After ||=: ${myNumber} (${yourNumber})`);

// Logical NULL: The assignment occurs if the value on the left is 'nullish'
// (null or undefined). 
// Otherwise, no assignment is made.
myNumber = 1;
yourNumber = 0;
let otherNumber = null;
myNumber ??= 2;
yourNumber = yourNumber ?? 2;
otherNumber ??= 2;
console.log(`After ??=: ${myNumber} (${yourNumber}) - (${otherNumber})`);

The Video

We have a video that explores the difference assignment operators.

Shameless Plug

Check us out everywhere!

Check out all our videos at: https://www.boringjavascript.com

Github Repository: https://github.com/TheVirtuoid/boringjavascript

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Discord: https://discord.gg/M2Hb6r628r

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: