SlightlyLoony
Tera Contributor

find_real_file.pngThere's just one more bitwise JavaScript operator left for us to talk about: the exclusive-or (aka XOR) operator, which is "^". There's also one more topic related to the bitwise operators that I'll cover today: how they can work as boolean operators through the magic of type coercion.

XOR and coercion — now doesn't that sound exciting? Or are you as confused as these giraffes?

If you run this code, 'z' will end up with 673:


var x = 593;
var y = 240;
var z = x ^ y;


Here's what it looks like in decimal, hex, and binary:

decimal hex binary
======= ====== ===================
x: 593 0x0251 0000 0010 0101 0001
y: 240 0x00f0 0000 0000 1111 0000
z: 673 0x02a1 0000 0010 1010 0001


There is no direct arithmetic equivalent for what the XOR operator does. It's easiest to understand in binary. For each bit position in 'x' where the corresponding bit in 'y' is a different, the resulting bit in 'z' is a 1. Where the 'x' and 'y' bits are the same, the result in 'z' is a zero. Many programmers think of XOR in a way that sounds different, but is actually exactly the same thing: for each bit position in 'y' that contains a 1, the corresponding bit in 'z' will be flipped, 1s for 0s and vice versa, from the corresponding bits 'x'.

And now for something completely different, but related...

Some of the bitwise operators ("&", "|", "^", and "~") all can be used much like a boolean operator. For instance, this code will print 'Test':

var x = true;
var y = false;
if (x | y)
gs.log('Test');


Why does this work? It's because 'x' and 'y' will both be coerced to numbers (1 and 0, respectively), the bitwise operator will produce the answer 1, and that will be coerced back to the boolean value 'true'. Trust me, it really does work like that. But why would you ever want to do such a thing? There are at least two reasons: First, you might not want short circuit evaluation. Consider this code:

if (x() & y())
gs.log('Test');


In this case, no matter what value 'x()' returns, the function 'y()' will still be called. If you used the normal '&&' operator, if 'x()' returned false then the function 'y()' wouldn't be called. The other case where you might find this useful is if you wanted an XOR operator — the only flavor of this operator available in JavaScript is the bitwise one.

3 Comments