javascript - evanmoran/quick GitHub Wiki

Debugging

console.log('a', 'b', ...);                // Output arguments to console
console.error('a', 'b', ...);              // Output error to console 
alert(value);                              // Output to popup window
debugger;                                  // Cause the debugger to break on this line

Types:

var numberValue = 5;
var stringValue = "hi";                   
var regexpValue = /ab+/ig;  
var regexpValue2 = new RegExp("ab+", "i", "g");                    
var dateValue = new DateTime(2000,0,1);    // January 1st, 2000

Arrays:

var arrayValue = [1,2,3];
array.length;                              // => 3
array[0];                                  // => 1
arrayValue.shift();                        // => 1 (removes first element)
arrayValue.push(4);                        // => [2,3,4]
arrayValue.concat([5,6]);                  // => [2,3,4,5,6]

For Loop (over Arrays):

var array = ["one","two","three"];
for (var i = 0; i < array.length; i++) {
  var item = array[i];  
}

For-In Loop (over Objects):

var obj = {name:"Evan", "hair color":"red", strength:9001};
for (var key in obj) {
  var value = obj[key]; 
}

Functions:

function namedFunction(a,b){
  return a+b;
}
namedFunction(1,2);                           // => 3

var assignedFunction = function(){            // Inline function
  return 5;
};
assignedFunction()                            // => 5

Object Literals:

var obj = {name:"Evan", "hair color": "brown"};   
obj.name = "Brian";                           // access with dot notation             
obj.age = 30;                                 // assignment can add keys
delete obj.name                               // `delete` keyword deletes
obj['hair color'] = 'red'                     // square bracket to access keys with spaces

Object Prototypes:

function Rectangle(width, height){
  this.width = width;
  this.height = height;
  this.area = function(){
    return this.width * this.height;
  }
}

var rect = new Rectangle(5,6);
rect.width                                     // => 5
rect.height = 10;                              // => 10
rect.area();                                   // => 50

Object Prototype Extension:

Rectangle.prototype.circumference = function(){
  return this.width*2 + this.height*2;
}

var rect = new Rectangle(5,6);
rect.circumference()                           // => 22