PBS - JavaScript Cheat-Sheet

Part of the Programming by Stealth Series

Comments (PBS 12)

// this is a comment
// anything after two slashes on a line ignored
  
/* this is also a comment */
  
/* This kind of comment can
spread over multiple lines */
  

Variables (PBS 12)

Declaration

var x; // declare a variable
var y = 4 // declare a variable with initial value
y = 'boogers'; // assign a value to a variable
  

Data Types

// numbers
var x = 12;
var y = -42;
var z = 3.1415
var a = -4.3;
var b = 2.4e12; // 2.4 x 10^12
  
// booleans
var x = true;
var y = false;
  
// strings
var x = 'a String';
var y = "also a string";
var z = "new line with \n, tab with \t";
  

Type Conversions

var x = parseInt(y); // convert to integer number
var a = parseDouble(b); // convert to floating point number
var c = String(d); // convert to string
var e = Boolean(f); // convery to boolean
  

Special Values

Operators

String Operators (PBS 12)

// concatenation
var x = 'a string' + ' another string';
  

Arithmentic Operators (PBS 12)

var x = 4 + 5; // addition
var y = 5 - 4; // subtraction
var z = 6 * 7; // multiplication
var a = 9 / 3; // division
var b = 6 % 4; // modulous
var c = 2 ** 5; // to the power of
  

Shutcut Operators (PBS 12)

x++; // x = x + 1;
x--; // x = x - 1;
x += y; // x = x + y;
x -= y; // x = x - y;
x *= y; // x = x * y;
x /= y; // x = x / y;
x %= y; // x = x % y;
x **= y; // x = x ** y;
  

Comparison Operators & Functions (PBS 17)

x === y // exactly equal
x == y // effectively equal
x < y // less than
x > y // greater than
x <= y // less than or equal
x >= y // greater than or equal
isNan(x) // check for NaN 
  

Logical Operators (PBS 13)

x && y // AND
x || y // OR
!x // NOT
  

Other Operators (PBS 16)

// 'type' of variables/vales
var s1 = typeof 4; // number
var s2 = typeof 4.2; // number
var s3 = typeof true; // boolean
var s4 = typeof "a string"; // string
var s5 = typeof Math.floor; // function
var s6 = typeof Math; // object
var s7 = [1, 2, 3]; // object - annoyingly

// test against prototype
var b1 = "test string" instanceof Array; // false
var b2 = [1, 2, 3] instanceof Array; // true
  

Strings (PBS 18)

JavaScript string manipulation functions are defined within the String prototype.

var s1 = "some sample string";

var len = s1.length;
var s2 = s1.toUpperCase();
var s2 = s1.toLowerCase();
var c = s1.charAt(4);
var a = s1.split(' '); // split into array on space
var b1 = s1.match(/[a-z]/);
var s2 = s1.replace(/[ ]/g, '_'); // replace spaces with _
var s2 = s1.replace(/(\d+)F/g, function(str, sub1){
	return Math.round((sub1 - 32) * (5 / 9)) + "C";
}); // convert F temps to C temps
  

Arrays (PBS 14)

JavaScript arrays are object with the Array prototype.

var a = []; // create empty array
var b = [1, 'boogers', false]; // create array with values
var x = a[4]; // get valye of element
a[4] = 'boogers'; // set value of element
  

Array Test

var a = [1, 2, 3];
var b = a instanceof Array; // true
  

Array Object Properties & Functions

// length of array
var a = [1, 2, 3];
var len = a.length;

// itterating over an array with callbacks (PBS 16)
a.forEach(function(v, i){
	pbs.say('value at index ' + i + ' is ' + v);
});

// reverse an array (PBS 18)
a.reverse();

// sort an array (PBS 18)
a.sort(); // lexical sort
a.sort(function(a, b){
  if(a < b) return -1;
  if(b < a) return 1;
  return 0;
}); // numeric sort with callback

// join into string (PBS 18)
var s1 = a.join(); // separate with ,
var s2 = a.join('\n'); // separate with new line character

// queue functions (PBS 18)
var q = [1, 2, 3];
var n = q.shift(); // n = 1, q = [2, 3]
q.unshift(1); // q = [1, 2, 3]

// stack functions (PBS 18)
var s = [1, 2, 3];
var n = s.pop(); // n = 3, q = [1, 2]
s.push(3); // q = [1, 2, 3]
  

Objects (PBS 17)

var obj = { // create object
	key1: "value 1",
	"key with space": 42
};
obj.key3 = 3.1415; // set value method 1
obj["key 4"] = false; // set value method 2
var b = obj.key1; // access method 1
var c = obj["key with space"]; // access method 2
  

Get Keys

var keysArray = Object.keys(obj);
  

JSON

// only plain objects can be converted to, or from JSON
var jsonString = JSON.stringify(myPlainObject);
var myPlainObject = JSON.parse(aJSONString);
  

Prototyped Objects

//
// create prototype Dummy
//

// constructor
function Dummy(v){
	this._value = v;
}

// accessor function
Dummy.value = function(){
	if(arguments.length > 0){
		this._value = arguments[0];
	}
	return this._value;
};

//
// Use prototype
//
var d = new Dummy(4);
d.value(5);
var dVal = d.value();
  

Regular Expressions (PBS 18)

In JavaScript, regular expressions are objects with the RegExp prototype.

// create RE
var intRE = /^[-]?\d+$/; // RE to test if entire string is int
var curRE = /([£$€])([-]?\d+([.]\d{2})?)/g; // RE to match all currency ammounts
  // note the g flag at the end of the RE for 'global'
  // also note sub-match grouping with perentheses
  
// test a value against an RE
var b1 = intRE.test('12'); // true
var b2 = intRE.test('12.5'); // false

// execute an RE against a string
var res1 = curRE.exec("no currencies in this string"); // null
var res2 = curRE.exec("My Dinner Cost $22.56"); // returns a results object:
  // res2[0] = '$22.56' (entire matched sting)
  // res2[1] = '$' (first submatch)
  // res2[2] = '22.56' (second submatch)
  // ...

// loop through multiple matches in single string
var testStr = "My Dinner Cost $22.56, much cheaper than the $55.04 from last week";
var res3;
while((res3 = curRE.exec(testStr)) !== null){
	//first time around res3[0] = $22.56
	// second time around res3[0] = $55.04
}
  

Control of Flow

Conditionals (PBS 13)

if(x == y){
	// do something
}
  

Loops (PBS 14)

// while loop
while(x == y){
	// do something
}

// for loop
for(var i = 0; i < x; i++){
	// do something
}
  

Functions (PBS 15 & PBS 16)

// define a function
function myFn(a, b){
	return a + b;
}

// invoke a function
var c = myFn(3, 4);

// function objects
var myFn2 = function(a, b){ return a - b; };
var d = myFn2(9, 6);
  

Exceptions (PBS 18)

// throw an error
throw new Error('Error Message Here');

// try/catch
try{
	// code that could throw error
}catch(err){
	// error message in err.message
}
  

Builtin Objects

Mathematical Constants & Functions (PBS 18)

// constants
var p = Math.PI; //Pi
var natLog10 = Math.LN10; // natural log of 10
var natlog2 = Math.LN2; // natural lof of 2
var euler = Math.E; // Euler's constant

// functions
var s = Math.sin(30);
var c = Math.cos(30);
var t = Math.tan(30);
var r1 = Math.round(2.4); // 2
var r1 = Math.round(2.5); // 3
var r2 = Math.round(2.6); // 3
var f = Math.floor(2.6); // 2
var c = Math.ceil(2.1); // 3
var a1 = Math.abs(23); // 23
var a2 = Math.abs(-23); // 23
var sr = Math.sqrt(64); // 8 - square root
var rand = Math.random(); // between 0 and 1
var rInt1 = Math.floor(Math.random() * 100); // 0 - 99
var rInt2 = Math.floor((Math.random() * 10) + 1); // 1 - 9