Forword
The following javascript examples and notation demonstrate a few alternatives to well known methods for common tasks.
Advanced Notation
Tilde Operator
The tilde operator “~” literally equates to “-(n+1)”. For example:
[codesyntax lang=”javascript”]
var a = ~1; //returns -2 var myString = "hello world"; ~myString.indexOf("hello"); //returns true
[/codesyntax]
Large Denary Numbers
Large denary numbers can be represented in short hand notation using the “e” operator. For example:
[codesyntax lang=”javascript”]
1e6; //returns 1000000.
[/codesyntax]
Floor Checking
Math.floor is the traditional way to check for floor number values. There are two other short hand methods for performing the same operation, “0|” and “~~”. For example:
[codesyntax lang=”javascript”]
var n = 1.23; Math.floor(n); //returns 1 ~~n; //returns 1 0|n; //returns 1
[/codesyntax]
Infinity
When checking for infinity you can use “Infinity” or you can use “1/0”. For example:
[codesyntax lang=”javascript”]
Infinity == 1/0; //returns true;
[/codesyntax]
Comma Chaining
The “,” can be used to chain statements together. For example:
[codesyntax lang=”javascript”]
with(document.body)style.backgroundColor="#fff",style.color="#000"
[/codesyntax]
Rounding
Another way to round numbers up is to use “n+.5|0” which is the equivalent to Math.round. However, this shortcut only works for positive numbers. For example:
[codesyntax lang=”javascript”]
3.2+0.5|0; //returns 3 3.5+0.5|0; //returns 4
[/codesyntax]
String Linking
Strings have a built in method that will trans form them into a link and return the HTML. For example:
[codesyntax lang=”javascript”]
"godlikemouse".link("http://www.godlikemouse.com"); //returns <a href="http://www.godlikemouse.com">godlikemouse</a>
[/codesyntax]
Bit Shifting
A quick way to divide by 2, or to raise something to the power of two is to shift the value. For example
[codesyntax lang=”javascript”]
50>>1; //returns 25
20>>1; //returns 10
2<<1; //returns 4
8<<1; //returns 16
[/codesyntax]