102 Class Reading, Blog

JavaScript operators

I’ve been discovering little oddities in JS lately, and I think it’s worthwhile to know about them, so let’s take a look.

bitwise operators

Bitwise operators treat operands (the values on either side of the operator) as a sequence of 32 bits (zeros and ones). These operators manipulate the values as binary representations and then return integers.

Left Shift Operator ( << ):

x << y

Shifts the x to the left by y bits.

Did you know:

x << y

is [almost*] the same as

x * Math.pow(2, y)

Example of usage:

console.log(10 * Math.pow(2, 10)); // logs 10240
console.log(10 << 10); // logs 10240

[*truncating happens!]

Right Shift Operator ( >> ):

x >> y

Shifts the x to the right by y bits.

Example of usage: You can parse hexadecimal values to get RGB color values

var hex = 'FFEFD5'; // papayawhip
var rgb = parseInt(hex, 16); // value: 16773077

var red   = (rgb >> 16) & 0xFF; // value: 255 
var green = (rgb >> 8) & 0xFF; // value: 239
var blue  = rgb & 0xFF; // value 213

(there are other bitwise operators in the spec, I’m just highlighting those interesting me to me here).

Note: JavaScript numbers are technically stored in 64-bits, but are treated as 32 bit when bitwise operators are used.

Also Note: There are a lot of dirty things you can do with bitwise operators, and I do not suggest them. One interesting implementation could be to store boolean flag information, one integer could hold 32 flags!

converting a string to an integer with + and -

I definitely do not recommend this, but it’s worth knowing about in case of extreme debugging.

var wat = +"7", 
    meep = -"7", 
    tinyKitten = +"tiniest of kittens";

console.log(wat); // logs 7
console.log(typeof wat); // logs "number"

console.log(meep); // logs -7
console.log(typeof meep); // logs "number"

console.log(tinyKitten); // logs NaN
console.log(typeof tinyKitten) // logs "number"

difference between i++ and ++i (same for decrement)

++i returns the value of i after being incremented

i++ returns the value of i before incrementing

var i = 0, j = 0;

console.log(++i); // logs 1
console.log(i++); // logs 0

! and type casting

Did you know that the ! operator will cast the type of objects, etc. as boolean?

var kitten = {}, 
    newKitten = !kitten, 
    newerKitten = !!kitten;

console.log(typeof kitten) // logs "object"
console.log(newKitten); // logs false
console.log(typeof newKitten); // logs "boolean"
console.log(newerKitten); // logs true

Remember the !! is not a new operator, it’s just the ! (negation) operator twice. It’s still interesting/strange to me that it would cast the type.

If this kind of thing is interesting to you, I highly recommend reading through the docs or MDN’s nice bitwise summary.

Also, I’d love if you’d leave your favorite lesser known JS features in the comments!