Skip to content

Instantly share code, notes, and snippets.

@psiborg
psiborg / gist:1569673
Created January 6, 2012 08:24
JS Date
var now = new Date();
now.toLocaleString(); // Tue Jun 14 2011 11:32:39 GMT-0400 (Eastern Daylight Time)
now.toGMTString(); // Tue, 14 Jun 2011 15:32:39 GMT (useful for setting browser cookies)
now.getTime(); // 1308065603585 (Unix epoch time in milliseconds since midnight of January 1, 1970)
@psiborg
psiborg / gist:1569677
Created January 6, 2012 08:25
JS Numbers
parseInt(x, 10) // 10 = decimal radix
parseFloat(x, 10)
x.toFixed(2)
@psiborg
psiborg / gist:1569679
Created January 6, 2012 08:25
JS Math
Math.PI // 3.141592653589793
Math.E // 2.718281828459045
Math.LN10 // 2.302585092994046
Math.LN2 // 0.6931471805599453
Math.LOG10E // 0.4342944819032518
Math.LOG2E // 1.4426950408889634
Math.SQRT1_2 // 0.7071067811865476
Math.SQRT2 // 1.4142135623730951
Math.random() // returns a number between 0 and 1
@psiborg
psiborg / gist:1569681
Created January 6, 2012 08:26
JS Try Block
try {
}
catch (ex) {
console.error(ex);
}
finally {
}
@psiborg
psiborg / gist:1569682
Created January 6, 2012 08:26
JS Switch Block
switch (letter) {
case "a":
case "e":
case "i":
case "o":
case "u":
// is a vowel
break;
case "y":
// is sometimes a vowel
@psiborg
psiborg / gist:1569685
Created January 6, 2012 08:27
JS Ternary Operator
var row = (cnt % 2 === 1) ? "odd" : "even";
@psiborg
psiborg / gist:1569687
Created January 6, 2012 08:27
JS If Block
if () {
}
else if () {
}
else {
}
@psiborg
psiborg / gist:1569691
Created January 6, 2012 08:28
JS While Loops
// fast
var i = myArr.length;
while (i--) {
console.log(i + ': ' + myArr[i]);
}
// while loop
var i = 0;
while (i < myArr.length) {
console.log(i + ': ' + myArr[i]);
@psiborg
psiborg / gist:1569696
Created January 6, 2012 08:29
JS For Loops
for (var i = 0; i < myArr.length; i++) {
//
}
for (var i = 0, ii = myArr.length; i < ii; i++) {
// 20% faster
}
for (var i = myArr.length; i--;) {
// 50% faster in reverse
@psiborg
psiborg / gist:1569698
Created January 6, 2012 08:29
JS Variables
var myInt = 0,
myFloat = 0.99,
myOct = 0123, // 83
myHex = 0xFFF, // 4095
myBigExp = 9.8e6, // 9800000
mySmallExp = 9.8e-6, // 0.0000098
myMax = Number.MAX_VALUE, // 1.7976931348623157e+308
myMin = Number.MIN_VALUE, // 5e-324
myStr = "Hello",
myBool = false,