11.4.8 bitwise NOT Operator ~

2010-05-17

UnaryExpression : ~ UnaryExpression

Code: (Meta Ecma)
funtion (~ UnaryExpression) {
var expr = evaluate(UnaryExpression);
var oldValue = ToInt32(GetValue(expr));
return ~oldValue; // "the bitwise completement to oldValue"
}


Note, this operator is often used as an easy short hand trick for Math.floor:

Code: (Ecma)
var n = 3.45;
alert(~~n); // 3

Except for negative numbers, it works as Math.ceil :)

Code: (Ecma)
var n = -3.45;
alert(~~n); // 3

An alternative to this is the OR operator: 0|n.