Bitwise XOR / caret ^ operator in JavaScript

Posted on Updated on

There is a XOR operator in JavaScript! Its the carrot symbol, ^, which is the symbol above the number 6 on a US keyboard.

In JavaScript the XOR operator can be written as such

x ^= y 	//shorthand
x = x ^ y 

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable.

The chances are if you are doing this in JavaScript its for a coding excessive where among an array of integers, all are duplicates except one. Thanks to the power of bitwise operations you just XOR all the values until you are left with a remainder. The gist of it is that two like numbers cancel each other out. To understand “how” take a deep dive into binary, which I may add in a future article. But to just “do”, look at the following

//this is pseudo code 
[3,4,5,4,3] //array with a single unique value
let x=0 // we will use this to handle our values 
//loop over every element
x^=3 //3
x^=4 //7
x^=5 //2
x^=4 //6
x^=3 //3

x is 5

Looping through the array we found the single unique value. The above won’t make sense in base10, you have to do it in binary if you want to make sense of it. Otherwise that is how to do it.


Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Connecting to %s